Expose a generic List<T> as a property: As per Object Oriented Principles and .NET standards exposing field variables as a public is against the rule of encapsulation.Properties are defined to expose the field variables.
Properties are defined to expose the field variables.
It is simple to make primitive type data such as string and int variables as property.
public string Name{get;set;}
But for Generic collection type variables, we need the collection instantiation while exposing the collection field.Otherwise, we will get null reference exception when trying to add members to the collection through the property.
This can be done in various ways. See 2 different ways explained below for Exposing a generic List<T> as a property.
1) Sample 1 – Exposing a generic List as a property by using constructor
class Class1
{
//List Property
public List<string> MyList
{ get; set; }
//Initialize MyList in constructor
public Class1()
{
MyList = new List<string>();
}
}
Access the generic list property,
private void Form1_Load(object sender, EventArgs e)
{
//Use of sample 1
Class1 c1 = new Class1();
List<string> strList = c1.MyList;
strList.Add("Rajeev");
}
2) Sample 2- Old model property declaration with private instance variable.
class Class2
{
//private instance
private List<string> myList2= new List<string>();
//Property
public List<string> MyList2
{
get { return myList2; }
}
}
We can access this generic list property as below,
private void Form1_Load(object sender, EventArgs e)
{
//Use of sample 2
Class2 c2 = new Class2();
List<string> strAddresses = c2.Addresses;
strAddresses.Add("TechyMedia");
}
Leave a Reply