1

Let's assume, we have following class:

public class foo 
{
    private string something
    public string Something
    {
        get { return something; }
        set { something = value; }
    }
}

If we don't need to use field something, we can write it shortly, as:

public class foo
{
    public string Something { get; set; }
}

It's OK.

But is there a way to short-write following class:?

public class foo 
{
    private List<string> something = new List<string>()
    public List<string> Something
    {
        get { return something; }
        set { something = value; }
    }
}

EDIT:

OK, found How do you give a C# Auto-Property a default value?

And since c# 6 we can write:

public List<string> Something { get; set; } = new List<string>();

Thanks for attention.

Community
  • 1
  • 1
  • 1
    there is a DefaultValueAttribute. But im afraid it will not work for reference types... – Mat Sep 23 '16 at 07:43
  • 3
    Dupicate of http://stackoverflow.com/questions/40730/how-do-you-give-a-c-sharp-auto-property-a-default-value – Mat Sep 23 '16 at 07:45
  • 1
    @Mat the `[DefaultValueAttribute]` doesn't _assign_ a value to a property, it just notifies editors and such what value you will be applying to it by default. – C.Evenhuis Sep 23 '16 at 07:46
  • @C.Evenhuis Thx for the clarification. Didn't knew that ;-) – Mat Sep 23 '16 at 07:48

0 Answers0