C#

Exposing List as Property of Class in C#

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");
}
Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

1 year ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

1 year ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

1 year ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

1 year ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

1 year ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

1 year ago