Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this implicit conversion from int to uint work?

Using Casting null doesn't compile as inspiration, and from Eric Lippert's comment:

That demonstrates an interesting case. "uint x = (int)0;" would succeed even though int is not implicitly convertible to uint.

We know this doesn't work, because object can't be assigned to string:

string x = (object)null;

But this does, although intuitively it shouldn't:

uint x = (int)0;

Why does the compiler allow this case, when int isn't implicitly convertible to uint?

like image 780
Yuck Avatar asked Jan 25 '12 19:01

Yuck


People also ask

What happens in implicit conversion?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.

How does implicit conversion work c++?

Implicit type conversion also known as automatic type conversion is carried out by the compiler without the need for a user-initiated action. It takes place when an expression of more than one data type is present which in such an instance type conversion takes place to avoid data loss.

How do you prevent implicit type conversion?

You can avoid implicit type casting by instead using explicit type casting or by adding generated columns.

Is there an implicit conversion from dynamic to any type?

10.2.An implicit dynamic conversion exists from an expression of type dynamic to any type T .


1 Answers

Integer constant conversions are treated as very special by the C# language; here's section 6.1.9 of the specification:

A constant expression of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type. A constant expression of type long can be converted to type ulong, provided the value of the constant expression is not negative.

This permits you to do things like:

byte x = 64;

which would otherwise require an ugly explicit conversion:

byte x = (byte)64; // gross
like image 160
Eric Lippert Avatar answered Sep 24 '22 04:09

Eric Lippert