Consider this code:
static void Main()
{
int? a = new int?(12); // warning CS0219: The variable 'a' is assigned but its value is never used
int? b = 12; // warning CS0219: The variable 'b' is assigned but its value is never used
int? c = (int?)12; // (no warning for 'c'?)
}
The three variables a
, b
and c
are really equivalent. In the first one, we call the public instance constructor on Nullable<>
explicitly. In the second case, we utilize the implicit conversion from T
to T?
. And in the third case we write that conversion explicitly.
My question is, why will the Visual C# 5.0 compiler (from VS2013) not emit a warning for c
the same way it does for the first two variables?
The IL code produced is the same in all three cases, both with Debug (no optimizations) and with Release (optimizations).
Not sure if this warning is covered by the Language Specification. Otherwise, it is "valid" for the C# compiler to be inconsistent like this, but I wanted to know what the reason is.
PS! If one prefers the var
keyword a lot, it is actually plausible to write var c = (int?)12;
where the cast syntax is needed to make var
work as intended.
PPS! I am aware that no warning is raised in cases like int? neverUsed = MethodCallThatMightHaveSideEffects();
, see another thread.