1

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;  
    }  
}
Russ Bradberry
  • 10,705
  • 17
  • 69
  • 85

5 Answers5

8

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
  • 37,201
  • 11
  • 119
  • 156
1

You will have to initialize it in the constructor:

class MyClass {

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

  public String ShortProp { get; set; }

}
Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
0

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
  • 72,212
  • 42
  • 129
  • 156
0

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.

Marcin Deptuła
  • 11,789
  • 2
  • 33
  • 41
0

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

Community
  • 1
  • 1
Dmytrii Nagirniak
  • 23,696
  • 13
  • 75
  • 130