Re: What does this mean(Generics)
- From: qglyirnyfgfo@xxxxxxxxxxxxxx
- Date: Wed, 18 Jun 2008 12:43:37 -0700 (PDT)
What I find interesting about this example is that if you constrain T
to be a “struct” then you will get a compile error.
So why is it that when T its unconstrained and it can be a “class” –
or- **struct** you don’t get a compile error?
On Jun 18, 7:24 am, "Jon Skeet [C# MVP]" <sk...@xxxxxxxxx> wrote:
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: Jon Skeet [C# MVP]
- Re: What does this mean(Generics)
- References:
- What does this mean(Generics)
- From: Tony
- Re: What does this mean(Generics)
- From: Jon Skeet [C# MVP]
- What does this mean(Generics)
- Prev by Date: Re: Threading advice: How to wait for all threads to complete without polling.
- Next by Date: What is the disadvantage if I don't implement IEnumerable<T>
- Previous by thread: Re: What does this mean(Generics)
- Next by thread: Re: What does this mean(Generics)
- Index(es):
Relevant Pages
|