Dimitar Tsonev
Dimitar Tsonev

Reputation: 3892

C#: Casting '0' to int

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

Upvotes: 12

Views: 5569

Answers (3)

Hans Passant
Hans Passant

Reputation: 942010

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

Upvotes: 18

Vyacheslav Volkov
Vyacheslav Volkov

Reputation: 4742

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

Upvotes: 0

Habib
Habib

Reputation: 223282

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

Upvotes: 5

Related Questions