Powered by Blogger.

Sunday, February 23, 2014

Create generics lists in C#.Net



In this post we will discuss about how to create lists in C#.Net. Also you can check out my previous posts:

- Increase column size in sql server 2008

- Page.IsPostBack Property in Asp.Net

- Get control value using JavaScript with master page in Asp.Net

We can create list objects by by invoking the default constructor. In generic class List<T> we need to specify the type for the values of the list with the declaration.

Ex: var intList = new List<int>();

The default constructor creates an empty list. As soon as elements are added to the list, the capacity of the list is extended to allow four elements. If the fifth element is added, the list is resized to allow eight elements. If eight elements are not enough, the list is resized again to contain 16 elements. With every resize the capacity of the list is doubled.

But you can also define the size while declaration like below:

List<int> intList = new List<int>(10);

But programmatically also you can set or get the size like below:

Set Size:
intList.Capacity = 20;
Get Size:
int size = intList.Capacity;

Also you can initialize a list like below:

var intList = new List<int>() {1, 2};

You can add elements to a list by using the Add method:

var intList = new List<int>();
intList.Add(1);
intList.Add(2);



0 comments

Post a Comment