Monday, June 22, 2026

C# Examples to Explain why generic is needed and use of dynamic keyword

Suppose that you want to add two integers. For this, you create the following Adder method:
class Adder
{
    int x, y;
    public int Sum(int number1, int number2)
    {
        this.x = number1;
        this.y = number2;
        return this.x + this.y;
    }
}
The above example adds two integer numbers. To add two floating point numbers, we will have to create another method:
class Adder
{
    float x, y;
    public float Sum(float number1, float number2)
    {
        this.x = number1;
        this.y = number2;
        return this.x + this.y;
    }
    int a, b;
    public int Sum(int number1, int number2)
    {
        this.a = number1;
        this.b = number2;
        return this.a + this.b;
    }
}
Generics become useful when the logic stays same but type changes.(Read more here)
To avoid creating multiple methods for same operation on different datatypes, we use generic method. The following example shows generic method. We have replaced the datatype by T symbol, T is called type parameter, which accepts a type e.g. int, float, double etc. 
class Adder<T>
{
    private T x, y;
    public T Sum(T number1, T number2)
    {
        this.x = number1;
        this.y = number2;
        // Operator '+' cannot be applied to operands of type 'T' and 'T'
        return _number1 + _number2; // compiler throws exception here
    }
}
The above code throws exception because the type of x and y is unknown to compiler and as it cannot perform + operation on unknown types.

We get compiler error: Operator '+' cannot be applied to operands of type 'T' and 'T'

Now, we correct the above code to remove the exception:
class Adder<T>
{
    T x, y;
    public T Sum(T number1, T number2)
    {
        dynamic x = number1; // type decided at runtime
        dynamic y = number2; // type decided at runtime
        return x + y;
    }
}
What is dynamic keyword?
If during the compilation, the datatype is not known, we can use dynamic datatype for a variable or type. At run time, the dynamic keyword will decide the datatype of the variable. 

Now, we create different closed generics e.g. Adder<int> and their instances.
class Program
{
    static void Main(string[] args)
    {
        Adder<int> adder = new Adder<int>();
        Console.WriteLine("Sum of two numbers:{0}", adder.Sum(2, 6));
        Adder<float> adder1 = new Adder<float>();
        Console.WriteLine("Sum of two numbers:{0}", adder1.Sum(2.2f, 5.6f));
        Adder<double> adder2 = new Adder<double>();
        Console.WriteLine("Sum of two numbers:{0}", adder2.Sum(2.2, 5.6));
        Console.ReadKey();
    }
}

We get sum for different datatypes using same generic method. This is the advantage of using generics in C#. It improves the code efficiency and type safety. 

👽👽 Still we can create closed generic like Adder<string>. The Sum will then throw exception at runtime. There is always Chance of Incorrect Type Argument. We can use constraint in generics to avoid this situation. We will see it later.

Thus, using generics, it is possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

Advantages of Generics
Generic classes and methods combine reusability, type safety, and efficiency in a way that their non-generic counterparts cannot. 
  • Reusability:- Same generic class/method can be used with different datatypes.
  • Type Safety:- The generic class is instantiated with a certain datatype. For example, Adder<float> adder = new Adder<float>(); the adder object can add only floating point numbers. If double datatype numbers will be used to add two numbers with this adder then compiler will throw exception.
  • Efficiency: Same generic methods or classes for different datatypes, the code size is reduced which in turn increases the efficiency of the code.
Generics are most frequently used with collections and the methods that operate on them. More we can read at Microsoft Site

Another Example, Swap numbers
class DemoSwap
{
    static void Swap(int a, int b)
    {
        Console.WriteLine("Before swap:{0} {1}", a, b);
        int temp;
        temp = a;
        a = b;
        b = temp;
        Console.WriteLine("After swap:{0} {1}", a, b);
    }
}
Generic version
class DemoSwap
{
    static void Swap<T>(T a, T b)
    {
        T temp;
        temp = a;
        a = b;
        b = temp;
    }
}
class Program
{
    static void Main(string[] args)
    {
        int a = 2, b = 3;
        Console.WriteLine("Before swap:{0} {1}", a, b);
        Swap(a, b);
        Console.WriteLine("After swap:{0} {1}", a, b);
        Console.ReadKey();
    }
}

No comments:

Post a Comment

Hot Topics