The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,482 other followers

Archive for October 15th, 2013

.NET/C#: suffixes for compiler number literals (via: Stack Overflow)

Posted by jpluimers on 2013/10/15

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 to 1 whereas
1.000000000000001m evaluates to 1.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 Integer literals (C#) and 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 »

Posted in .NET, .NET 1.x, .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, .NET 4.5, Algorithms, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Floating point handling, Software Development | Leave a Comment »

%d bloggers like this: