General comparison of two objects

The naive question I know, and after two years of experience, I was stuck to answer it.

I just need to create a general method, and this method can take int, double, float and compare them and find a larger value:

object ComapreMethod(object obj1, object obj2)
{ 
    if(obj1 > obj2)
    {
        return obj1;
    }

    return obj2;
}

I want to call it for int, short, ushort, float, double, ... etc. that I am really stuck on how to compare between obj1 and obj2. I can’t write it, by the way above. I know that it is naive, but I do not know.

+4
source share
4 answers

Well, you can change your method signature using generics:

TType ComapreMethod<TType>(TType obj1, TType obj2) where TType : IComparable

and change your code in the method from if(obj1>obj2)to if (obj1.CompareTo(obj2) > 0)(and don't forget to handle cases obj1 and obj2 equal to zero).

, IComparable, ints, doubleles floats.

+8

, , , Math.Max ( MSDN):

var myMax = Math.Max(input1, input2);

input1 input2, . , int, float double, (, int double double)).

, , , :

double CompareMethod(double obj1, double obj2) 
{
    if (obj1.CompareTo(obj2) > 0)
    {
        return obj1;
    }
    return obj2;
}

, ints double .. , , , ints , int , .

,

+4

, . int .

    static void Main(string[] args)
    {
        decimal p = 15.5m;
        int q = 5;

        Console.WriteLine(CompareTo<int, decimal, decimal>(q, p));

    }

    public static T3 CompareTo<T1, T2, T3>(T1 value1, T2 value2) 
        where T3:IComparable
    {
        T3 p = ConvertTo<T3>(value1);
        T3 q = ConvertTo<T3>(value2);

        if(p.CompareTo(q) >= 0)
        {
            return p;
        }
        else
        {
            return q;
        }
    }

    public static T ConvertTo<T>(object value)
    {
        try
        {
            return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
        }
        catch(Exception ex)
        {
            return (T)(typeof(T).IsValueType ? Activator.CreateInstance(typeof(T)) : null);
        }

    }

T1 - , T2 - , , T3 , (, ..).

+1

. CompareTo :

void Main()
{
    float a = 2;
    float b = 1;
    ComapreMethod(a, b); // A > B

    short c = 0;
    short d = 3;
    ComapreMethod(c, d); // A < B

    int e = 1;
    int f = 1;
    ComapreMethod(e, f); // A == B
}

// you can change the return type as you wish
string ComapreMethod(object a, object b)
{ 
    var result = Convert.ToInt32(a.GetType().GetMethods().First(o => o.Name == "CompareTo").Invoke(a, new object[] { b }));

    if (result == 0)
        return "A == B";
    else if (result > 0)
        return "A > B";
    else if (result < 0)
        return "A < B";
    else
        return "I don't know...";
}
0

Source: https://habr.com/ru/post/1569293/


All Articles