MC.
MC.

Reputation: 363

Comparing objects of value type N

What is the best way to compare objects of value type N? So I want to do a String, Integer, DateTime, etc comparison depending on the type of the object.

Upvotes: 4

Views: 172

Answers (3)

Wil P
Wil P

Reputation: 3371

static void Main(string[] args)
{

    Console.WriteLine(Compare<int>(1, 3));
    Console.WriteLine(Compare<string>("wil", "test"));
    Console.WriteLine(Compare<DateTime>(DateTime.Now, 
        DateTime.Now.AddDays(-1)));
    Console.ReadKey();
}

static int Compare<T>(T a, T b) where T : System.IComparable
{
    System.IComparable comparer = a;
    return comparer.CompareTo(b);
}

Upvotes: 0

EgorBo
EgorBo

Reputation: 6142

Every simple types implements IComparable interface

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245399

IEqualityComparer<T>

Where T is the type you want to compare.

IEqualityComparer(T) Interface (System.Collections.Generic)

...you could also fall back on Object.Equals() and ValueType.Equals()

Upvotes: 7

Related Questions