William Duffy

Glasgow Based ASP.NET Web Developer

C# Literal Types

When you are specifying literal numeric values in your code you will, on occasion, have to give the compiler a heads-up on the expected type from the declaration.

For example, the literal value 5.3 will, by default, be assumed to be a double. As such, the following

1
float result = 5.3 / 12.4;

will result in the exception

Cannot implicitly convert type ‘double’ to ‘float’. An explicit conversion exists (are you missing a cast?)

You could cast the value but that would create an unneccessary overhead and result in messy code.

1
2
3
float result = (float)5.3 / (float)12.4; 
or
float result = (float)(5.3 / 12.4);

The most suitable way to approach this is to advise the compiler on the literal type. You do this by applying a suffix to your literal.

1
float result = 5.3f / 12.4f;

This can also be used when passing a literal as a parameter in a method signature.

1
MyObject.MyMethod(12.5m);

A table of the most common literal type declarations can be seen below.

1
2
3
4
5
6
var x = 1m;  // decimal
var x = 1f;  // float
var x = 1d;  // double
var x = 1l;  // long
var x = 1u;  // uint
var x = 1ul; // ulong
Bookmark and Share
  Kick It on DotNetKicks.com

Tagged as , , , + Categorized as ASP.NET, C#

3 Comments

  1. Welcome back Duffy! been a while since the last post!

    Ninja

    p.s I’m sure I told you all this at B.D Network :-)

  2. I had no idea you could do this - i’ve been using the Cast method which, as you say, is messy - however I thought it was a limitation.

    Excellent post - now I have tons of code to refactor :(

Trackbacks & Pingbacks

  1. Tweets that mention C# Literal Types | William Duffy -- Topsy.com

    [...] This post was mentioned on Twitter by wduffy, Caspar Kleijne. Caspar Kleijne said: RT @wduffy: New blog post, http://www.wduffy.co.uk/blog/c-literal-types/ - Just a little quick helpful post this one. #csharp #aspnet [...]

Leave a Reply