tags:

views:

665

answers:

7

What is the actual difference between a long and an int in C#? I understand that in C/C++ long would be 64bit on some 64bit platforms(depending on OS of course) but in C# it's all running in the .NET runtime, so is there an actual distinction?

Another question: can an int hold a long(by cast) without losing data on all platforms?

+16  A: 

an int (aka System.Int32 within the runtime) is always a signed 32 bit integer on any platform, a long (aka System.Int64) is always a signed 64 bit integer on any platform. So you can't cast from a long with a value above Int32.MaxValue or below Int32.MinValuewithout losing data.

thecoop
+4  A: 

int is 32 bits in .NET. long is 64-bits. That is guaranteed. So, no, an int can't hold a long without losing data.

There's a type whose size changes depending on the platform you're running on, which is IntPtr (and UIntPtr). This could be 32-bits or 64-bits.

Gonzalo
+1  A: 

Sure is a difference - In C#, a long is a 64 bit signed integer, an int is a 32 bit signed integer, and that's the way it always will always be.

So in C#, a long can hold an int, but an int cannot hold a long.

C/C++ that question is platform dependent.

Walt W
+1  A: 

In C#, an int is a System.Int32 and a long is a System.Int64; the former is 32-bits and the later 64-bits.

C++ only provides vague guarantees about the size of int/long, in comparison (you can dig through the C++ standard for the exact, gory, details).

Josh Petrie
A: 

I think an int is a 32-bit integer, while a long is a 64-bit integer.

Doug R
+1  A: 

int in C#=> System.Int32=>from -2,147,483,648 to 2,147,483,647.

long in C#=> System.Int64 =>from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

If your long data exceeds the range of int, and you use Convert.ToInt32 then it will throw OverflowException, if you use explicit cast then the result would be unexpected.

Anton Setiawan
A: 

I can heartily recommend Charles Petzold's free book: .NET Book Zero in PDF download form; it covers CLR/CTS type system basics really clearly and logically.

Gordon Mackie JoanMiro