raju_shrestha Posted September 11, 2004 Posted September 11, 2004 (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 September 11, 2004 by raju_shrestha Quote
Administrators PlausiblyDamp Posted September 11, 2004 Administrators Posted September 11, 2004 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
raju_shrestha Posted September 12, 2004 Author Posted September 12, 2004 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. Quote
Administrators PlausiblyDamp Posted September 12, 2004 Administrators Posted September 12, 2004 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 and on the calls in Main Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
raju_shrestha Posted September 12, 2004 Author Posted September 12, 2004 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. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.