Question

I have a static readonly List<string> ValidatedProperties = new List<string>(); inside of a custom class Foo, and in Foo's constructor I call

protected Foo()
{
    foreach(var prop in properties)
    {
        ValidatedProperties.Add(prop.Name);
        Console.WriteLine(prop.Name);
    }
}

It prints out as expected when I create a new Foo, however, it does this every time I create a new Foo.

Is ValidatedProperties being re-written each time I create another Foo object? or is it just displaying each property again because of Console.WriteLine?

Was it helpful?

Solution 2

I've got a feeling that what you are trying to do is have a single list that is shared between all instances of Foo, but is populated only once. Perhaps a static constructor is what you want:

static Foo()
{
    // note that properties needs to be static too!
    foreach(var prop in properties)
    {
        ValidatedProperties.Add(prop.Name);
        Console.WriteLine(prop.Name);
    }
}

public Foo()
{
    // regular constructor for creating an instance of Foo
}

Although, unless properties is coming from some external source (e.g. a database, webservice, file), it would be a lot easier to just populate ValidatedProperties when you declare it:

static readonly List<string> ValidatedProperties = new List<string>() { "foo", "bar" }

You could even use a ReadOnlyCollection<string> to prevent anybody adding to it later:

static readonly ReadOnlyCollection<string> ValidatedProperties = 
    new ReadOnlyCollection<string>(new string[] {"foo", "bar" });

OTHER TIPS

Every time you create an instance of Foo, you add a entries to ValidatedProperties.

Readonly only means the List can not be replaced with another list - it does not mean the content of the list can not change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top