Why operation not allowed with generic data types

  • Thread starter Thread starter Raju Shrestha
  • Start date Start date
R

Raju Shrestha

I am trying to learn Generics with C# and tried following code:

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace Generics
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("5+2 = " + Math.Add<int>(5,6));
Console.WriteLine("1.2 + 3.3 = " + Math.Add<float>(1.2F,
3.3F));
Console.ReadLine();
}
}

class Math
{
public T Add<T>(T a,T b)
{
return (a + b);
}

}
}

It gives the error message "Operator '+' cannot be applied to operands
of type 'T' and 'T'". Is this C# bug or something else. Appreciate for
experts help.
thanks!
 
It gives the error message "Operator '+' cannot be applied to operands
of type 'T' and 'T'". Is this C# bug or something else. Appreciate for
experts help.
thanks!

The whole point is that the compiler doesn't know what a 'T' is. Just
because you happened to use an 'int' and a 'float' which do support the +
operator, there's no way it can tell that you won't try to do Math.Add
<boolean>, which doesn't support the + operator.

On a side note, you probably shouldn't use the name 'Math' for the class
since that's already used by the .NET framework. Unless of course, you're
just trying to make things simple for us.... :)

-mdb
 
It looks like you need to overload the + operator in order to provide the
necessary details to the runtime to be able to add the two types together.

HTH,

Greg
 
Raju Shrestha wrote:

You can't just overload the '+' operator as someone suggested, because
the compiler has no idea what type T will be until runtime.
 
Jeremy Gailor said:
Raju Shrestha wrote:

You can't just overload the '+' operator as someone suggested, because
the compiler has no idea what type T will be until runtime.

Good point. I really have to get into Generics more.
 
Back
Top