Re: What does this mean(Generics)



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

.



Relevant Pages

  • Re: C99 Question
    ... avoid shadowing type names to avoid confusion. ... When I compile a C program as C++, I make a habit of also testing the ... I tend to constrain myself to the very large subset of C ... You must be glad you cought it. ...
    (comp.lang.c)
  • Unable to display custom control in the toolbox of Visual Studio IDE
    ... Here's the line I use to compile: ... I also tried comparing the two dll files in IDLSAM.EXE to see if there's a difference between the Assembly I generated manually and the assembly Visual Studio created, but there's absolutely no difference at all. ... Edward ...
    (microsoft.public.dotnet.framework.aspnet.webcontrols)
  • Re: timeouts
    ... Comparing my version of s-osprim.adb and the one from ACT, ... Of course you'll then need to compile s-osprim.adb with the compiler ... option that lets to recompile system components (which I don't recall ...
    (comp.lang.ada)
  • Re: Linux 2.6.22 released
    ... this with gcc 20070627 then everything works, if I compile it with gcc ... to compile the rest of the kernel. ... and have so many trivial differences (register allocation ... we can *try* to see if it might be obvious enough from comparing the ...
    (Linux-Kernel)