Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct comparisons of C# Value types

I have read the following statement regarding to the comparison of C# value types in C# in Depth, Second Edition several times.

page 77,

When a type parameter is unconstrained (no constraints are applied to it), you can use == and != operators, but only to compare a value of that type with null. You can’t compare two values of type T with each other.

...

When a type parameter is constrained to be a value type, == and != can’t be used with it at all.

If I understand (I don't think so) it correctly, it basically tells me that you cannot use == or != to compare two value types. Why why why?

It will be better if a simple example can be given for this case. Can someone give me a little idea what the above paragraph tries to convey?

like image 315
q0987 Avatar asked Jun 03 '11 02:06

q0987


People also ask

What is similar to C?

The best alternative is Java. It's not free, so if you're looking for a free alternative, you could try C++ or Rust. Other great apps like C (programming language) are Go (Programming Language), C#, Lua and Perl.

Is C similar to C+?

C++ is a superset of C, so both languages have similar syntax, code structure, and compilation. Almost all of C's keywords and operators are used in C++ and do the same thing. C and C++ both use the top-down execution flow and allow procedural and functional programming.

How is C++ different from C?

C has no support for functions and operator overloading. It also does not have any namespace feature and functionality of reference variables. C++, on the other hand, supports both of the functions and operator overloading. It also has the namespace feature and the functionality of reference variables.

Is provided by C++ but not C?

Which of the following type is provided by C++ but not C? Explanation: C++ provides the boolean type to handle true and false values whereas no such type is provided in C.


1 Answers

It simply means this when constraining to a value type (second paragraph)

static bool TryToCompare<T>(T first, T second) where T : struct
{
    return first == second; // not legal
    return first.Equals(second); // legal
}

Without the value-type constraint on the generic, it also says this (first paragraph)

static bool TryToCompare<T>(T first, T second) 
{
    return first == second; // not legal
    return first == null; // legal
    return first.Equals(second); // legal
}

If you constrain T to a reference type, you can get away with using ==

static bool TryToCompare<T>(T first, T second) where T : class
{
    return first == second; // legal
    return first == null; // legal
    return first.Equals(second); // legal
}
like image 104
Anthony Pegram Avatar answered Sep 26 '22 22:09

Anthony Pegram