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 ?
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 ?
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>();
}
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;
}
}
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.
Not in the same statement. You can do it in the constructor body though