Generic problem

raju_shrestha

Member
Joined
Nov 23, 2003
Messages
14
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 static T Add<T>(T a,T b)
{
return (a + b);
}

}
}

It gives the compile time 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!
 
Last edited by a moderator:
At runtime T could be any class at all, and as such may not have the + operator defined - hence you cannot reliably use the + operator here.
 
PlausiblyDamp said:
At runtime T could be any class at all, and as such may not have the + operator defined - hence you cannot reliably use the + operator here.

But cant it be done using some kind of constraints for say Numerics (or some other way). Such kind of situations occur in many cases and the real benefit of Generics can be achieved if it supports these.
 
PlausiblyDamp said:
http://blogs.msdn.com/csharpfaq/archive/2004/03/12/88913.aspx might be worth a read as it covers this area. Also note that you didnt need the <int> and <float> on the calls in Main

Thanks for the link. Also thanks for the note, which I knew that it can implicitly infer the integer and float types.

Im going through the article. But still I feel .Net Generics is at its infant stage and I believe its architects will finally realize the benefit for allowing the operations once it gets mature.

I really appreciatef for your response.
 
Back
Top