C# & Hex Notation Confustion

How would it know it's a long unless you told it so? ;)

In this case it's not neccesary, but there are circumstances where you need to specifiy that your integer constant is a long and not a short. That's when the 'L' at the end comes in useful.
 
Okay... but

Code:
const int IntConst = 5555L;

Doesn't compile, I think I'm missing the point....

Its because you can't implicitly cast a long to an int, it creates a possible loss of precision. Explicitly cast it and it will work.

Ex:
const int IntConst = (int)5555L;

Code:
object a = 123;
object b = 123L;
Console.WriteLine(a.GetType().ToString());
Console.WriteLine(b.GetType().ToString());

Returns:
System.Int32
System.Int64
 
Last edited:
I honestly can't think of an example for the L suffix

.NET will implicitly cast a value if there won't be a loss of precision. It recognises values by the lowest common denominator. Hence

long x = 1;

It will recognises 1 as a Int32 and cast it implicitly to a Int64

While if you try this:

float f = 1.0;

The compile will fail because it recognises 1.0 as a double, so the implicit cast fails.

You can add a literal suffix F or you could cast it.

float f = (float)1.0;
float f = 1.0F;
 
I honestly can't think of an example for the L suffix

I can :)

long l = 65535 * 10;

will give a different result to

long l = 655325L * 10L;

in the first case 65532 and 10 are both treated as shorts, so their result is stored in a short and then assigned to the long, so it will be wrong.

In the second case the two values are treated as longs so the result is stored temporarily in a long before being assigned.
 
Sorry, forgot that ints are 32-bit and longs are 64.

Try
long l = 1000000 * 1000000;
vs.
long m = 1000000L * 1000000L;

The first one gives you an error in C#, in C++ is used to give you a warning and fail at runtime.
 
Top
Sign up to the MyBroadband newsletter
X