Friday, February 14, 2020

c# generics


generics to write a class or method that can work with any data type. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.
It helps you to maximize code reuse, type safety, and performance

·         Use generic types to maximize code reuse, type safety, and performance.
·         The most common use of generics is to create collection classes.

public class GenericList
{
    public void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList list1 = new GenericList();
        list1.Add(1);

        // Declare a list of type string.
        GenericList list2 = new GenericList();
        list2.Add("");

        // Declare a list of type ExampleClass.
        GenericList list3 = new GenericList();
        list3.Add(new ExampleClass());
    }
}

No comments:

Post a Comment