How do I tell C# what kind of literal number I want?

Published 12 March 04 02:18 AM

If you need to tell C# that you want it to treat a literal as a particular type of number, you may do so by adding a number type suffix at the end of the literal you provide. For example:

1u; // An unsigned int
1l; // A signed long
1ul; // An unsigned long
1f; // A System.Single floating-point number;
1d; // A System.Double floating-point number
1m; // a System.Decimal floating-point number

This is somewhat important because sometimes you must match a literal to the signature of something or specify the value to 'defeat' an implicit cast behavior you don't like. For example, Hashtable names = new Hashtable(100, 0.1); won't compile because the constructor takes parameters (int, float) and the above is (int, double). The line should read Hashtable names = new Hashtable(100, 0.1f);

A full listing of the suffixes is in the Grammar portion of the C# specification (appendix A in the ECMA specification, appendix C in the MS specification). The suffixes are also detailed in the Literals section of the specification (9.4.4 of the ECMA specification, 2.4.4 of the MS specification).

[Author: Jon Skeet]

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Chris Burrows .NET Blog said on March 16, 2004 5:10 AM:
# .ERN said on March 25, 2004 4:09 PM:
# Grant said on May 8, 2004 8:25 PM:
This is the perfect reason why the compiler issues a warning when using a lower-case 'l' as a suffix, it looks *exactly* like the number '1'. Please use an upper-case 'L'.
# RebelGeekz said on December 28, 2004 4:55 AM:
[http://itpeixun.51.net/][http://aissl.51.net/][http://kukuxz003.freewebpage.org/][http://kukuxz001.51.net/][http://kukuxz003.51.net/][http://kukuxz005.51.net/][http://kukuxz002.51.net/][http://kukuxz004.freewebpage.org/][http://kukuxz007.51.net/][http://kukuxz001.freewebpage.org/][http://kukuxz006.51.net/][http://kukuxz002.freewebpage.org/][http://kukuxz004.51.net/][http://kukuxz008.51.net/][http://kukuxz009.51.net/][http://kukuxz005.freewebpage.org/][http://kukuxz006.freewebpage.org/][http://kukuxz007.freewebpage.org/][http://kukuxz009.freewebpage.org/]
# Bat's Blog said on February 16, 2005 6:25 PM:

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker