Create generics lists in C#.Net

This C#.Net tutorial, we will discuss, what is generics in and how to generics lists in C#.Net.

C#.Net Generics

Generics allow you to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific type at compile time.

Generics allow creating classes that support any type. Basically, it creates a class template that supports any type, And when you instantiate that class, you can specify what type you want to use.

Below is an example:

List lst = new List { 1, 2, 3 };

Here it is a List of interger type. It should take only integer values.

If you try to insert string values like below:

lst[0] = "";

Then it will give a compile-time error like can not implicitly convert type string to int.

Below is an example of a Generics class:

public class UserMaster
public Int64 UserID
public string Name
public string EmailID

UserMaster userMaster = new UserMaster();
userMaster.UserID = 1234;
userMaster.Name = "AspDotNetHelp";
userMaster.EmailID = "";

List<> lstUserMaster = new List<UserMaster>();

Create generics lists in C#.Net

We can create list objects 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 resizes 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>();

You may like following tutorials:

Hope this tutorial helps to learn generics and how to create generics lists in C#.Net

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.