Sadiq
Sadiq

Reputation: 838

C# in Depth: Type Constraint

I was reading C# in Depth and came across this which i can understand:

When it’s constrained to be a reference type, the kind of comparison performed depends on exactly what the type parameter is constrained to be.

But can't understand this:

If it’s further constrained to derive from a particular type that overloads the == and != operators, those overloads are used.

I will highly appreciate if someone will explain this through example... Plzz

Upvotes: 2

Views: 171

Answers (2)

Peter Ritchie
Peter Ritchie

Reputation: 35881

When it's constrained to a reference type without an operator== and operator!= (the first quote) then the compiler knows it has no knowledge about equality of the type other than use Object.Equals--which merely does a reference comparison.

If the constraint is a type that does have an operator== and operator!=, the compiler knows enough that there is something other that Object.Equals that it can use for equality and hence uses the type's operator== to test for equality (which is usually something other than a reference comparison).

Upvotes: 1

Oded
Oded

Reputation: 498952

== and != are the equality and non-equality operators.

These can be overridden by different types - in types that have overridden them, if used as generic type constraints, this implementation will be used for comparisons using these operators.

With your example, that line doesn't apply as you don't have an additional constraint to a type that overrides ==:

static bool AreReferencesEqual<T> (T first, T second) where T : class
{ 
  return first==second; 
}

If you had such a type (that was also open to inheritance) then:

If the type that T is constrained to does not overload ==, a simple reference equality test will be done (the default Object implementation).

If, however the type does overload == (say a business entity where if two instances have the same id they are considered identical), that implementation will be used, regardless if you pass in that type or an inheriting type.

Consider an Person class that overrides ==. And a method that is constraining the type parameter to be a Person. If you have an Employee that derives from Person and also overrides ==, when using == in the generic method, the == used will be the Person one.

Upvotes: 3

Related Questions