Re: What does this mean(Generics)
- From: "Jon Skeet [C# MVP]" <skeet@xxxxxxxxx>
- Date: Wed, 18 Jun 2008 05:24:30 -0700 (PDT)
On Jun 18, 1:17 pm, "Tony" <johansson.anders...@xxxxxxxxx> wrote:
It says "Another limitation that you need to be aware of is that using the
operator == and != are
only permitted when comparing a value of a type supplied to a generic type
to null.
That is, the following code works.
Here if T is a value type then it is always assumed to be non-null, so in
the above
code Compare always return true;"
The question is what does they mean with the text saying "using the operator
== and != are
only permitted when comparing a value of a type supplied to a generic type
to null."
It means that if T is unconstrained you can't do:
T foo = ...;
T bar = ...;
if (foo == bar)
If you constrain T to be a reference type (i.e. use "where T : class")
then reference identity comparisons will be used and you can compare
two values
If you constrain T to be derived from a type which overloads == and !=
then those overloads will be used. This is *not* polymorphic - only
overloads the compiler can guarantee at compile-time are used. For
instance, if you had a constraint "T : IEnumerable<char>" and used
"string" then == would still mean reference identity, rather than
using the == overloaded for string.
Jon
.
- Follow-Ups:
- Re: What does this mean(Generics)
- From: qglyirnyfgfo
- Re: What does this mean(Generics)
- References:
- What does this mean(Generics)
- From: Tony
- What does this mean(Generics)
- Prev by Date: What does this mean(Generics)
- Next by Date: Analyze .SQL, .CSV and .XLS-files
- Previous by thread: What does this mean(Generics)
- Next by thread: Re: What does this mean(Generics)
- Index(es):
Relevant Pages
|