1

How can we combine c# accessor declaration and initialization

List<string> listofcountries= new List<string>();
and 
List<string>listofcountries {get;set;}

Is there a way to combine these to statements ?

knowledgeseeker
  • 1,123
  • 3
  • 15
  • 31

4 Answers4

7

You can't at the moment. You will be able to in C# 6:

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

You can even make it a read-only property in C# 6 (hooray!):

List<string> Countries { get; } = new List<string>();

In C# 5, you can either use a non-automatically-implemented property:

// Obviously you can make this read/write if you want
private readonly List<string> countries = new List<string>();
public List<string> Countries { get { return countries; } }

... or initialize it in the constructor:

public List<string> Countries { get; set; }

public Foo()
{
    Countries = new List<string>();
}
Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
0

Only in C# 6.

what i usually like to do is :

  private List<string> list;
  public List<string> List
  {
     get
     {
         if(list == null)
         {
            list = new List<string>();
         }

         return list;  
     }
  }
eran otzap
  • 11,845
  • 20
  • 77
  • 133
0

You could either use the constructor, or create a custom getter/setter:

Constructor

public class Foo
{
    public Foo()
    {
        listofcountries = new List<string>();
    }

    public List<string> listofcountries { get; set; }
}

Custom Getter/Setter

private List<string> _listofcountries;
public List<string> listofcountries
{
    get
    { 
        if (_listofcountries == null)
        {
            _listofcountries = new List<string>();
        }
        return _listofcountries;
    }
    set { _listofcountries = value; }
}

For what it's worth, convention is to have public properties be camel-cased: ListOfCountries rather than listofcountries. Then the private instance variable for the property would also be camel-cased, but with the first letter lowercase: listOfCountries rather than _listofcountries.

UPDATE Skeet FTW, as usual. Once C# 6 hits, then his answer will be the best way, hands down. In lesser versions, you're stuck with the methods I posted.

Chris Pratt
  • 221,046
  • 31
  • 356
  • 415
  • Your custom getter is inappropriate, as if it's null and you use the getter twice, you'll get two different lists - you'd want to assign to `_listofcountries`. – Jon Skeet Sep 05 '14 at 12:38
  • Right. That's what I get for posting too quickly. Fixed. – Chris Pratt Sep 05 '14 at 12:47
  • There's also the "write a custom property, but don't bother making it lazy" approach, which means it's just a two-liner... there's no indication that the OP *wants* the allocation to be lazy. – Jon Skeet Sep 05 '14 at 12:49
0

Not in the same statement. You can do it in the constructor body though

Adrian Zanescu
  • 7,706
  • 6
  • 33
  • 52