River
River

Reputation: 1487

c# static class declaration

Hi the intent of the code below is to return a static class which holds a related set of data. Can you recommend how I can do this better?

public class People
{
    //want info to be setup in this class, so it can be accessed elsewhere
    public static readonly string[] ab = { "ALBERT", "EINSTEIN"};       
    public static readonly string[] dk = { "DONALD", "KNUTH" };

   //is this efficient or instantiated once per access? IF SO HOW CAN I DO THIS BETTER? 
    public static readonly Info AB = new Info(ab, 100); 
    public static readonly Info DK = new Info(dk, 80);

}

public class Info
{
    private string[] _name;
    private int _age;

    public string[] Name { get{ return _name}; }
    public int Age { get { return _age; } }

    public Info(string[] n, int a)
    {
        _name = n;
        _age = a;
    }
}

Upvotes: 1

Views: 359

Answers (1)

Chopin
Chopin

Reputation: 1452

is this efficient or instantiated once per access?

If you mean the moment at when the instances of Info are constructed, they are built before the first access to the member. So no matters how many times you call People.AB, the object will be the same.

From MSDN about Static Classes and Static Class Members:

Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.

If you want to make your instances of Info totally immutable (as Daniel says, the values of _name could be changed once you get a reference to the array), you can change the type of _name and its property accesor to:

private List<string> _name;

public IList<string> Name { get { return _name.AsReadOnly(); } }

Hope I've understood your needs!

Upvotes: 3

Related Questions