This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.

Tuesday, 26 February 2013

Overview of type suffixes

I'd like to bring your attention to an area of the C# specification which is misunderstood by many:

Type Suffixes

Type suffixes are individual characters that you can append to 'any code representation of a value' (called a literal in .NET) which allows you to specify it's exact type.  They only relate to numbers - of which can be defined as one of two forms:

- Integer literals (Whole numbers)
- Real literals (More precision)

If you type 10 into your source code, the compiler will automatically interpret that as an integer type, however if you were to type 10.1 this would be automatically interpreted as a real type (because of the decimal point - the full rules are in the C# specification).  To demonstrate this I'll use the var keyword, which assumes a type based on it's initial assignment:

however if I type 10.1 I get a double (the default for a real literal):

Type suffixes allow you to override these defaults.

For example what if I wanted to specify a float?  Well it turns out there's a type suffix for this, f (single is a synonym for float):

and similarly decimal has m:

The point here is that the literal's type is defined the moment you enter it into the source code and not by the variable you are assigning it to. This becomes important in the scenario when you want to define a type where there isn't an implicit conversion available between the default type, and the variable being defined:

Here you're essentially attempting to store a number inside a box that's too small (usually referred to as a narrowing conversion).  To get around this you need to tell the compiler you actually wanted a decimal:

I understand this topic is somewhat basic, but I believe deserved an overview nonetheless.

No comments:

Post a Comment