Search This Blog

Friday 4 December 2015

Add two numbers using generics c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Generic
{
    class Program
    {
        public void Calculator<T>(T a, T b)
        {
            Console.WriteLine(a + b);
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.Calculator<int>(10, 20);

            Console.ReadLine();
        }
    }
}

When you compile the project you will get the following Error

Operator '+' cannot be applied to operands of type 'T' and 'T'

Note:-
Because T is unknown to the compiler and it doesn't know how to add T values. It also doesn't know the result type of T, in this case the addition.

To resolve this error you can use dynamic keyword.

Dynamic keyword sets the value at runtime, which type of value passed.
After using dynamic keyword your method look like this.

public void Calculator<T>(T a, T b)
{
            dynamic num1 = a;
            dynamic num2 = b;

            Console.WriteLine(num1 + num2);
}

Note:-
dynamic  keyword introduced in .NET 4.0 
You can use any character instead of T

1 comment: