Consider this simple program which compiles fine in Visual Studio 2015:
public class Program
{
enum Direction
{
Up,
Down,
Left,
Right
}
static void Main(string[] args)
{
// Old style
Console.WriteLine(string.Format("The direction is {0}", Direction.Right));
Console.WriteLine(string.Format("The direction is {0}", (int)Direction.Right));
// New style
Console.WriteLine($"The direction is {Direction.Right}");
Console.WriteLine($"The direction is {(int)Direction.Right}");
}
}
... which outputs as expected:
The direction is Right
The direction is 3
The direction is Right
The direction is 3
However, Visual Studio 2015 keeps suggesting a "Quick Action" on this line specifically:
// "Cast is redundant" warning
Console.WriteLine($"The direction is {(int)Direction.Right}");
It insists that the (int)
"cast is redundant", and suggests as a potential fix to "Remove Unnecessary Cast", which of course is wrong, as it would change the result.
Interestingly, it doesn't give me any warning for the equivalent statement:
// No warnings.
Console.WriteLine(string.Format("The direction is {0}", (int)Direction.Right));
Can someone provide a reasonable explanation for this false-positive when using an expression in an interpolated string?
This is a known bug.
A temporary fix has been proposed for the mean time:
For people experiencing this bug in VS2015 now, a workaround is to suppress warning IDE0004 in the build tab of the property pages of the affected project.
This has been fixed and merged into master on 09/09/2015 in PR 5029.
The explicit cast is unnecessary in a way - you can (and probably should) use a format specifier:
$"The direction is {Direction.Right:d}"
But yeah, the warning is silly - it should suggest this change, not just removing (int)
. The compiler has quite a few kinks - fortunately, most seem to be very easy to work around.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With