This project is read-only.


C# - Roslyn suggests dubious refactoring options for integral type casts.


While browsing some of my code unsing VS2013 with Roslyn End User Preview, I noticed some casts were faded out, and I was proposed to remove them. However, doing so would either change the meaning of the program or prevent it from compiling.

Now, I'll provide some code to showcase the two problems with the suggestion "Remove Unnecessary Cast".
  1. Producing invalid code
byte b = 0;
int i = 0;
s += i == 0 ? (byte)0 : (byte)0;
Here, Visual Studio suggests removing both of the casts to (byte) in the ternary expression. This would, however, produce an invalid C# program.
  1. Producing valid but wrong code
byte b = 254;
ushort u = (ushort)(sbyte)b;
Here, Visual Studio proposes to remove the cast to sbyte, and then proposes to remove the now really useless cast to ushort.
This time, it will produce valid C# code, but the meaning will be changed dramatically. (254 vs 65534)


srivatsn wrote Jul 30, 2014 at 12:21 AM

Manish, can you take a look at this please?

angocke wrote Aug 15, 2014 at 1:12 AM

Fixed in changeset 6bfd738a6d146a479e8877ab99be0e0424525fe8