Of course this is not only an issue for Guid
. The same behavior is seen with any struct
type which is not a pre-defined type of C# provided that the struct
overloads operator ==
in the usual way. Other examples in the framework include DateTime
and TimeSpan
.
This deserves a compile-time warning since, while technically legal because of the lifted operator, this is not a useful comparison since it always gives false
. As such, it is an indication of a programmer mistake.
As Eric Lippert said in his answer, the compile-time warning existed with the Visual C# 2.0 compiler. In versions 3.0 through 5.0, the warning was accidentally omitted (for these "user-defined" struct
types, but not for pre-defined value types like int
, and not for enum types).
Since C# 6.0 (based on Roslyn), the compiler detects this code problem once again. However, because of backwards compatibility(?!), the warning is not issued unless you compile your code with the so-called strict feature.
To enable strict when you use a .csproj
file (most usual case), unload the project from Visual Studio, edit the file, insert the XML element:
<Features>strict</Features>
into each <PropertyGroup>
(there will usually be more than one) of the .csproj
file. You then get the warning (can be "promoted" to an error if you use Treat warnings as errors).
If you cannot edit the .csproj
and if you call msbuild.exe
from the command line for compiling, use the switch:
/p:Features=strict
to msbuild.exe
.
If you do not use .csproj
files because you compile directly with csc.exe
(the C# compiler), use the switch:
/features:strict
to csc.exe
on the command line.