views:

268

answers:

5

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;  
    }  
}
+1  A: 

You will have to initialize it in the constructor:

class MyClass {

  public MyClass() {
    ShortProp = "Some string";
  }

  public String ShortProp { get; set; }

}
Martin Liversage
A: 

I never want to declare a variable in the class defination. Do it in the constructor.

So following that logic, you can inlitailze your ShortProp in the constructor of your class.

David Basarab
A: 

The only way you can do this, is in constructor.


public List<ClinicalStartDate> ClinicalStartDates { get; set; }

public ObjCtor()
{
   ClinicalStartDates = new List<ClinicalStartDate>;
}

That's probably not what you wanted to hear though.

Ravadre
+8  A: 

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>();
    }
}
Bruno Reis
@Downvoter: any suggestions on how to improve the answer? What don't you like about it?
Bruno Reis
A: 

C# 3.5 does not support automatic initialization of automatic properties.
So yes, you should use a constructor.
And your question is a duplicate.

Dmytrii Nagirniak