1

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;
    }
}
1
  • 1
    fyi, the values Name are mutable. Commented May 26, 2012 at 0:05

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

2 Comments

why did you choose to use IList<string> in your getter? since the private variable _name is already using a concrete List<string> type?
That's because the AsReadOnly() method returns a ReadOnlyCollection<T> instance, whichs implements the IList<T> interface, but doesn't extends the List<T> class, so it couldn't be converted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.