TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

Exposing List<T> As A Property Of Class In C#

Generic collection type variables need to be Instantiated while exposing else will end up in null reference exception when try to add members to the collection through property accessor.Two different steps are explained in this article.

As per .NET standards exposing field variables as public is against rule of encapsulation.Properties are defined to expose the field variables.It is straight forward to make normal string,int variables to property.

public string Name{get;set;}


But for Generic collection type variables we need the collection Instantiation while exposing the collection field,else will receive null reference exception when try to add members to the collection through property accessor.

This can be done in various ways.See 2 different ways explained below.

1) Sample 1

class Class1
    {
        //List Property
        public List<string> MyList
        { get; set; }

        //Initialize MyList in constructor
        public Class1()
        {
           MyList = new List<string>();
        }
  }   


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; }
    }

}


Usage:

private void Form1_Load(object sender, EventArgs e)
  {
             //Use of sample 1
            Class1 c1 = new Class1();
            List<string> strList = c1.MyList;
            strList.Add("Rajeev");

            //Use of sample 2

            Class2 c2 = new Class2();
            List<string> strAddresses = c2.Addresses;
            strAddresses.Add("TechyMedia");
  }

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading