C#: Casting '0' to int

后端 未结 3 1951
Happy的楠姐
Happy的楠姐 2020-12-20 13:29

I saw a code like this:

private readonly object[] m_Values = { (int)0, (int)0 };

What\'s the idea to cast 0 to int? Isn\'t it int by \'defa

相关标签:
3条回答
  • 2020-12-20 14:03

    It is not necessary. I'd assume the programmer got bitten before. I'll post it as a puzzler, which overload will be called in this program?

    using System;
    
    class Program {
        static void Main(string[] args) {
            Foo.Bar(0);
            Console.ReadLine();
        }
    }
    
    class Foo {
        public static void Bar(byte arg)  { Console.WriteLine("byte overload"); }
        public static void Bar(short arg) { Console.WriteLine("short overload"); }
        public static void Bar(long arg)  { Console.WriteLine("long overload"); }
    }
    
    0 讨论(0)
  • 2020-12-20 14:06

    I think it is pointless to have it like that, but the only place I think that can be useful is where the original coder wanted to prevent this value to be casted to other data type. Consider the example:

    object[] m_Values = { (int)0, (int)0 };
    Int16 item = (Int16) m_Values[0];
    

    or

    object[] m_Values = { (int)0, (int)0 };
    Int64 item = (Int64)m_Values[0];
    

    The above would result in

    Specified cast is not valid.

    but following would work:

    object[] m_Values = { (int)0, (int)0 };
    int item = (int)m_Values[0];
    
    0 讨论(0)
  • 2020-12-20 14:07

    C# defaults to Int32 when you declare an integer literal without supplying a type hint (as long as the literal fits into an Int32, otherwise it will go to Int64). From here:

    In C#, literal values receive a type from the compiler. You can specify how a numeric literal should be typed by appending a letter to the end of the number. For example, to specify that the value 4.56 should be treated as a float, append an "f" or "F" after the number

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