The Wiert Corner – irregular stream of stuff

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

  • My work

  • My badges

  • Twitter Updates

  • My Flickr Stream

    20140508-Delphi-2007--Project-Options--Cannot-Edit-Application-Title-HelpFile-Icon-Theming

    20140430-Fiddler-Filter-Actions-Button-Run-Filterset-now

    20140424-Windows-7-free-disk-space

    More Photos
  • Pages

  • All categories

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

    Join 1,776 other followers

.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 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:

Unlike VB.NET, C# ommits a few suffixes (for instance short is missing) as they are not needed.

The suffixes have been there since the first version of C#, but only reached the FAQ in 2004: How do I tell C# what kind of literal number I want? – C# Frequently Asked Questions – Site Home – MSDN Blogs.

–jeroen

via: C# compiler number literals – Stack Overflow.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: