NtFreX
NtFreX

Reputation: 11357

simple generic type compare

I have a MyUser class with a generic identifier type. The UserManager class has a method GetByIdentifier which compares the given identifier with the known user identifiers. The problem is that I get the following error:

Operator '==' cannot be applied to operands of type 'TUserIdentifier' and 'TUserIdentifier'

public MyUser<TIdentifier>
{
    public TIdentifier Identifier { get; set; }
}

public class UserManager<TUser, TUserIdentifier>
    where TUser : MyUser<TUserIdentifier>
{
    protected List<TUser> userStore = new List<TUser>();
    protected TUser GetByIdentifier(TUserIdentifier identifier)
    {
        return userStore.FirstOrDefault(c => c?.Identifier == identifier);
    }
}

When I change the signature of the UserManager to the following I cannot define simple types as int, string ect as the TUserIdentifier anymore.

public class UserManager<TUser, TUserIdentifier>
    where TUser : MyUser<TUserIdentifier>
    where TUserIdentifier : class

A workaround would be to use the Integer, String etc. classes.


Another thing I tried doing is the following signature but it did not work

public class UserManager<TUser, TUserIdentifier>
    where TUser : MyUser<TUserIdentifier>
    where TUserIdentifier : IComparable

Should I go for the Integer, String, etc classes or is there another way?

Upvotes: 2

Views: 95

Answers (1)

InBetween
InBetween

Reputation: 32740

The problem here is that the compiler can not be sure that you are not mistakenly performing a reference equality check between two value types; ReferenceEquals(1, 1) will always be false, reference equality doesn't make sense with value types!

Because your generic types are not constrained to reference types (class constraint) the compiler simply dissallows the == operator because its default implementation is precisely reference equality.

To avoid this issue simply use the virtual Equals method.

Upvotes: 4

Related Questions