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,519
  • 17
  • 67
  • 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
  • 36,131
  • 11
  • 113
  • 152
1

You will have to initialize it in the constructor:

class MyClass {

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

  public String ShortProp { get; set; }

}
Martin Liversage
  • 100,656
  • 22
  • 201
  • 249
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
  • 70,191
  • 42
  • 128
  • 155
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,541
  • 2
  • 31
  • 40
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
  • 22,978
  • 12
  • 70
  • 126