Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic value equality (identity) in C#

Tags:

c#

generics

What is the best (most concise and optimal) way to compare two instances of same generic type such that reference types are compared for identity (same object, so not calling Equals) and value types for value equality.

Currently I do this:

static bool IdentityEquals<T>(T x, T y)
{
    return typeof(T).IsValueType
        ? EqualityComparer<T>.Default.Equals(x, y)
        : ReferenceEquals(x, y);
}
like image 816
Marcin Wisnicki Avatar asked Jun 24 '13 22:06

Marcin Wisnicki


1 Answers

You should be able to just use object.Equals for value types:

 return typeof(T).IsValueType
    ? object.Equals(x, y)
    : ReferenceEquals(x, y);
like image 147
D Stanley Avatar answered Sep 21 '22 13:09

D Stanley