I have created a class and self initialized it in the file - is this the best way to use it? I have another Constant class that I can use but I am unable to use this for some reason in my project, do they need to be consts?
File: test.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DH.Models
{
public class test
{
public string testSourceCollection { get; set; }
public string testSourceKey { get; set; }
public string testSourceDatabase { get; set; }
public string testSourceCluster { get; set; }
public string testSourceTimestamp { get; set; }
public test[] testDetails = {
new test{
testSourceCollection = "SourceCollection",
testSourceDatabase = "SourceDatabase ",
testSourceKey = "SourceKey ",
testSourceTimestamp = "SourceTimestamp "
},
new ProviderRecon
{
testSourceCollection = "testSourceCollection2",
testSourceDatabase = "testSourceDatabase2",
testSourceKey = "testSourceKey2",
testSourceTimestamp = "testSourceTimestam2",
testSourceCluster = "testSourceCluster2"
}
};
}
}
I would like to use in my Worker.cs file as such
public class Worker : BackgroundService
{
var test = test.testDetails;
Console.WriteLine("2nd test: " test.testSourceCluster )
//Prints "2nd test: testSourceCluster2"
}
CodePudding user response:
You probably want testDetails
to be static. You can't access (non-static) members using a type. Change public test[] testDetails = ...
to public static test[] testDetails =...
However, you have a lot of non-standard namings there, which make this code confusing to read. The class test
should be called Test
instead. The line var test = test.testDetails;
is hard to read otherwise (and probably won't compile). Same is true for your Worker class. That piece of code won't compile.
CodePudding user response:
Every time when you create an instance of your class, testDetails property is initialized with new array. If you create 1000 instances for each instance testDetails is initialized with new array.
You can use static field/property to avoid create multiple instances with the same array. static keyword
Or use static readonly property/field to avoid create multiple instances with the same array. static readonly properties/fields can be initialized with static constructors. Static constructors