C#: Casting '0' to int

大兔子大兔子 提交于 2019-12-18 07:35:25

问题


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 'default' ?


回答1:


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"); }
}



回答2:


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];



回答3:


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



来源:https://stackoverflow.com/questions/16456507/c-casting-0-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!