Search code examples
c#.netcomparableicomparable

Can I check if an object is comparable to some other type?


I'd like to write some code like this:

if (obj.IsComparableTo(integer))
    Console.Write("successed");

Is this possible? If not, is there an alternative way of determining this?


Solution

  • i've found it :

            public bool isComparable<t>(object o)
            {
                try
                {
                    object r = (t)o;
                }
                catch
                {
                    return false;
                }
                return true;
            }
    

    to use it:

    if (isComparable<int>(32).ToString())
        Console.WriteLine("success");
    else
        Console.WriteLine("fail");