A long while I avoided using suffixes to force the C# compiler into a specific type and – like Marc Gravell – used type-catst like (decimal)3.1415. I found out the hardway: it doesn’t work all the time.
(decimal)1.000000000000001
evaluates to1
whereas
1.000000000000001m
evaluates to1.000000000000001
.
In the former case, the computer parses the literal as a double and then casts it to a decimal. – Joe Albahari Apr 15 ’11 at 6:02
My main reason for using the casts was that I kept forgetting the suffixes needed to force a literal to be of a specific type. Hence this post.
The suffixes and casts are not limited to use in consts: any place where a numeric literal is used, you can use a suffix to force a compile time type.
Though documented in sections 2.4.4.2 Integer literals (C#) and 2.4.4.3 Real literals (C#) of the C# standard and appendix C. Grammar (C#). That standard does not contain a comprehensive list, much after I wrote this post I found Value Types Table (C# Reference).
This post only lists the C# suffixes. Abel Braaksma published a blog entry Overview of type suffixes in C# and VB.Net.
StackOverflow user sixlettervariables has this (slightly) edited list:
var y = 0f; // y is single/float
var z = 0d; // z is double
var r = 0m; // r is decimal
var i = 0U; // i is unsigned int
var j = 0L; // j is long (note capital L for clarity)
var k = 0UL; // k is unsigned long (note capital L for clarity)
Some more background info: Read the rest of this entry »