Generics in C#

This article is to understand how to use the Generic in C#.

Sometimes we landed up with the situation where we repeat the code just because of different datatype used as the parameter. Generics play a good role in removing this repeatation of code.

To understand how to use the Generic let’s take a simple example.

Below is the code sample for three different classes

 class ClassInt {
        public bool Success { get; set; }
        public int Data { get; set; }
    }

    class ClassString {
        public bool Success { get; set; }
        public string Data { get; set; }
    }

    class ClassBoolean{
        public bool Success { get; set; }
        public bool Data { get; set; }
    }

If you look at the structure of these classes you will find the common structure, the only difference is the “Data” property with different data type.

This repeatation of code can easily be removed using the Generic data type inside the class.

This can be done using the below code.

 class Generics{
        public bool Success { get; set; }
        public T Data { get; set; }
    }

To access the class with different datatype for the Data property is as follow

//Use of Generic
var GenericIntegerClass = new Generics() { Success = true, Data = 10, };
Console.WriteLine(GenericIntegerClass.Success);
Console.WriteLine(GenericIntegerClass.Data);

var GenericStringClass = new Generics() { Success = false, Data = "WhiteX", };
Console.WriteLine(GenericStringClass.Success);
Console.WriteLine(GenericStringClass.Data);
//End

Note*: var is the VARIABLE used for implicit typing. Whenever you declare the variable with Var keyword compiler convert the variable to object defined in the right side of equal sign. Remember you cannot create object using var and assign it null as value.

Advertisements

#generics