Re: What does this mean(Generics)



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
.



Relevant Pages

  • Re: VB.NET Overloading problem/question
    ... > Because ToString is overridden, ... You are comparing two totally ... > Overriding is on actaul methods of the class. ... overloads contain types that are related in an ancestor-descendant ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Pedants
    ... However Jacob publishes only his binaries. ... I would be interested to see what you think you are comparing against ... were compiled by the same compiler program and with identical compiler ... PUSH ...
    (comp.lang.c)
  • Re: optimized code
    ... > All depends on what exactly you are measuring, how you are comparing and ... > take advantage of the back-end optimizer which can do a better job than ... > produced by the C++ compiler, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: 64-bit on the horizon? (Was Re: Vista Requirement Already)
    ... Win64 code is very often slower than win32 because the size of the ... by 1.3 thought the i386 compiler contains more code because ... you be comparing cross-compilation results? ... So I still don't see how you conclude that memory footprint ...
    (borland.public.delphi.non-technical)
  • Re: gcc vs. Sun Workshop/Forte / was: Re: Can someone do us a favour? Need core trace back.
    ... > up to him today by finding out why our AIX compiler was failing). ... > to the more recent versions of gcc. ... > Not much use for comparing to Forte but interesting that you can get ... The Mozilla.org default for Sun Workshop is "-xO4" but I reduce that to ...
    (comp.unix.solaris)