Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

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!

Edited by raju_shrestha
Posted
At runtime T could be any class at all' date=' and as such may not have the + operator defined - hence you cannot reliably use the + operator here.[/quote']

 

But can't 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.

Posted
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 didn't 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.

 

I'm 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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...