Comparing objects of type N

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

+4
source share
3 answers
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); } 
0
source
 IEqualityComparer<T> 

Where T is the type you want to compare.

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

... you can also return to Object.Equals() and ValueType.Equals()

+7
source

Each simple type implements the IComparable interface

+1
source

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


All Articles