1

I want to make some generic methods like this one

public static T maxValue(T value1, T value2 )       
{
    if(value1>value2)
        return value1;
    else
       return value2;    
}

And use it like

max<string>.maxValue("john","john");

My question is what should be the return type of the maxValue function and how to use operators like +, =, <, > etc with generic types?

I know that T has no defined data type. I need the improvement this code.

DavidG
  • 113,891
  • 12
  • 217
  • 223
deepak pandey
  • 101
  • 3
  • 13
  • 1
    for comparing use `value1.CompareTo(value2) > 0` but for adding or subtracting you cant. you may use dynamic type instead which may lead to runtime errors. – M.kazem Akhgary Nov 28 '15 at 13:21
  • @JameyD That is incorrect, generic methods doesn't have access to the operators on the generic type parameters. Best one can do is to require `IComparable`, as ArghyaC's answer shows. – Lasse V. Karlsen Nov 28 '15 at 14:54
  • @ArghyaC Your edit was not good here. Do no put tags in the question titles. – DavidG Nov 28 '15 at 21:38
  • @DavidG hmm...I followed this example from [ask] page - *"Good: How can I redirect users to different pages based on session data in PHP?"* It is more search friendly I'd say. – Arghya C Nov 28 '15 at 21:42
  • @ArghyaC From [help](http://stackoverflow.com/help/tagging): *You should not force a tag into your title* – DavidG Nov 28 '15 at 22:02
  • @DavidG There are different opinions on where it is appropriate to include tag in title (e.g. http://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title, http://meta.stackoverflow.com/questions/256724/tag-in-question-title-battle etc.), but for now I'm good as long as OP gets some help from the answer :) – Arghya C Nov 28 '15 at 22:12

1 Answers1

3

You can do this. This, you can use for comparisons like ==, >, < etc., but not for operations like +, -.

Here, we are using for > (return type would be T, same as input types)

public static T maxValue<T>(T value1, T value2) where T : IComparable<T>
{
    if (value1.CompareTo(value2) > 0)
        return value1;
    else
        return value2;
}

Usage

var maxInt = maxValue(3, 7); //=> 7
var maxDouble = maxValue(34.89d, -9.6d); //=> 34.89
Arghya C
  • 9,805
  • 2
  • 47
  • 66
  • Unfortunately there's no quick solution for `+`, `-` like this. You can check http://stackoverflow.com/questions/8523061/how-to-verify-whether-a-type-overloads-supports-a-certain-operator and http://stackoverflow.com/questions/5997107/is-there-a-generic-constraint-i-could-use-for-the-operator – Arghya C Nov 28 '15 at 22:03