2

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.

Community
  • 1
  • 1
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • With the Roslyn end user preview, it's `b` and `c` (but not `a`) that generate warnings. Mono generates warnings for all of them... I'd strongly discourage that use of `var`, by the way... if you have to cast, you might as well declare the variable that way. – Jon Skeet Jun 18 '14 at 14:13
  • Noticed the same behavior as @JonSkeet in VS2015 preview. The error code of `CS0219` is actually linked to this post through bing/VS2015 :P. Either way, seems to me that there is nothing wrong with what is happening, but also seems to me that the code that highlights/flags unused variables could be **improved**. – Erti-Chris Eelmaa Jan 13 '15 at 15:39

0 Answers0