C# compiler number literals

后端 未结 3 740
误落风尘
误落风尘 2020-11-30 02:54

Does anyone know the full list of C# compiler number literal modifiers?

By default declaring \'0\' makes it an Int32 and \'0.0\' makes it a \'Double\'. I can use the

相关标签:
3条回答
  • 2020-11-30 03:33

    You might want to start by looking at the C# language spec. Most of the types are listed in there, and have a suffix:

    • L = long
    • F = float
    • U = uint
    • ulong's are a little different
    • m = decimal (money)
    • D = double

    Of course, if you stop using var then you get around the whole problem, and your code becomes more readable (ok, thats subjective, but for something like this, it's more readable by other people:

    var x = 0; //whats x?
    float x = 0; //oh, it's a float
    byte x = 0; // or not!
    
    0 讨论(0)
  • 2020-11-30 03:53
    var y = 0f; // y is single
    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)
    

    From the C# specification 2.4.4.2 Integer literals and 2.4.4.3 Real literals. Take note that L and UL are preferred as opposed to their lowercase variants for clarity as recommended by Jon Skeet.

    0 讨论(0)
  • 2020-11-30 03:54

    If you don't want to have to remember them, then the compiler also accepts a cast for the same purpose (you can check the IL that the effect is the same - i.e. the compiler, not the runtime, does the cast). To borrow the earlier example:

        var y = (float)0; // y is single
        var z = (double)0; // z is double
        var r = (decimal)0; // r is decimal
        var i = (uint)0; // i is unsigned int
        var j = (long)0; // j is long
        var k = (ulong)0; // k is unsigned long
    

    And for the record, I agree that "var" is a bad choice here; I'll happily use var for a SortedDictionary<SomeLongType, SomeOtherLongType>, but for "int" it is just lazy...

    0 讨论(0)
提交回复
热议问题