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.