Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio 2015: Invalid "Cast is redundant" warning in interpolated string expression

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?

like image 331
sstan Avatar asked Aug 25 '15 14:08

sstan


2 Answers

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.

like image 123
Jeroen Vannevel Avatar answered Sep 25 '22 06:09

Jeroen Vannevel


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.

like image 31
Luaan Avatar answered Sep 22 '22 06:09

Luaan