C#: Casting '0' to int

后端 未结 3 1955
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: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];
    

提交回复
热议问题