More Effective C# – Generics part I

Generics – Interfaces, Classes, etc.

  • .NET developer should use IEquatable interface if he wants to override the System.Object.Equals method
  • public interface IEquatable<T>
        bool Equals(T other);
  • If you need to perform comparisons on a type defined in another library you should use IEqualityComparer interface
  • public interface IEqualityComparer<T>
        int Equals( T x, T y);
        int GetHashCode(T obj);

    Moreover, if you want to write own comparator, you can extend EqualityComparer generic class:

    public class MyClassComparer : EqualityComparer<MyClass>
        public override bool Equals(MyClass x, MyClass y)
            return EqualityComparer<MyClass>.Default.Equals(x, y);
        public override int GetHashCode(MyClass obj)
            return EqualityComparer<MyClass>.Default.GetHashCode(obj);

    To compare objects, the best idea is to use IComparable interface

    public interface IComparable<T>
        int CompareTo(T other);
  • To represent a null value of some type you should use Nullable struct
  • [SerializableAttribute]
    public struct Nullable<T>
    where T : struct, new()


  • More Effective C# – 50 Specific Ways To Improve C#
  • MSDN

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s