Search code examples
c#.netpropertiesautomatic-properties

How to return a new instance of an object in C# Automatic Properties


Is it possible, using C# Automatic Properties, to create a new instance of an object?

in C# I love how I can do this:

public string ShortProp {get; set;}

is it possible to do this for objects like List that first need to be instantiated?

ie:

List<string> LongProp  = new List<string>(); 
public List<string> LongProp {  
    get {  
        return LongProp ;  
    }  
    set {  
         LongProp  = value;  
    }  
}

Solution

  • You can initialize your backing field on the constructor:

    public class MyClass {
        public List<object> ClinicalStartDates {get; set;}
        ...
        public MyClass() {
            ClinicalStartDates = new List<object>();
        }
    }
    

    But... are you sure about making this list a property with a public setter? I don't know your code, but maybe you should expose less of your classes' properties:

    public class MyClass {
        public List<object> ClinicalStartDates {get; private set;}
        ...
        public MyClass() {
            ClinicalStartDates = new List<object>();
        }
    }