C# Generics CompareValues


Generics.

namespace BrackeysGenericsVideo
{ // video time is 11:14 
    class Program {
        static void Main(string[] args)  {
            WriteLine(Utility.CompareValues(1, 2)); // False
            WriteLine(Utility.CompareValues(5, 5)); // True
            WriteLine(Utility.CompareValues(5, 5.0)); // False
            WriteLine(Utility.CompareValues(false,false)); // True
            WriteLine("");
            WriteLine(Utility.CompareTypes(1, 2)); // True
            WriteLine(Utility.CompareTypes("hello", 2)); // False
            WriteLine(Utility.CompareValues(5, 5.0)); // False
            ReadKey();
        }  // what if you used your custom objects, cow, chicken...
    }
    // This method below would be better placed into a 
    // class library with other utilities.
    public class Utility {
        // a method that checks if two unknown
        // types are equal and returns a bool
        public static bool CompareValues<T1, T2>(T1 value1, T2 value2)
        {
            return value1.Equals(value2);
        }
        public static bool CompareTypes<T1, T2>(T1 type1, T2 type2)
        {
            return typeof(T1).Equals(typeof(T2));
        }
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *