BRO1122: Use literal suffix notation instead of casting¶
1L instead of (long)1. Replaces StyleCop SA1139.
Example¶
Before¶
public class Limits
{
public long MaxBytes = (long)1024 * 1024 * 1024;
public float Scale = (float)0.5;
public decimal Fee = (decimal)2;
public long Offset = (long)-1;
}
After¶
public class Limits
{
public long MaxBytes = 1024L * 1024 * 1024;
public float Scale = 0.5F;
public decimal Fee = 2M;
public long Offset = -1L;
}
Why¶
A suffix says the literal's type directly; a cast makes the reader check whether a conversion happens.
How the fix works¶
The cast is replaced with the literal and the suffix for the type (U, L, UL, F, D, M; none for int).
A sign and parentheses stay where they were ((long)(1) becomes (1L)). When BRO1135 is off (init
turns it off for code that writes 0u), unsigned suffixes are written in lower case (6u, 1ul); L stays upper case.
Not reported¶
- Casts whose literal would have a different value.
(decimal)0.1234567890123456789goes throughdoubleand keeps 15 digits, while0.1234567890123456789Mkeeps all of them;(decimal)1.50is1.5, while1.50Mprints as1.50;(float)of a double literal can round differently than a float literal. The rule compares the cast's constant value with the new literal's and only reports exact matches. - Casts that don't change the type (
(int)1; those are IDE0004's), casts to other types ((short)1), casts of expressions ((long)(a + 1)), unsigned casts of negative numbers, casts with a comment inside, and a cast directly after-or+whose result would start with a sign (a-(long)-1would becomea--1L).
Compared with StyleCop¶
StyleCop checks only that the type stays the same, so its fix can change a decimal's value or scale. Otherwise the same positions and output.