Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't an Int64 equal to a long in C#?

People also ask

Is Int64 same as long?

In C#, long is mapped to Int64. It is a value type and represent System. Int64 struct. It is signed and takes 64 bits.

Is Int64 the same as BigInt?

BigInt is not the same as INT64 no matter how much they look alike. Part of the reason is that SQL will frequently convert Int/BigInt to Numeric as part of the normal processing. So when it goes to OLE or . NET the required conversion is NUMERIC to INT.

What is Int64 in C#?

Int64 is an immutable value type that represents signed integers with values that range from negative 9,223,372,036,854,775,808 (which is represented by the Int64. MinValue constant) through positive 9,223,372,036,854,775,807 (which is represented by the Int64. MaxValue constant.


long is Int64 in .NET; it is just an alias in C#. Your problem is casting the return value to long and unless we know the type coming back from your query for sure, we would not know why you get an error. SQL BigInt must be convertable to long.

If it is the COUNT(*) which is coming back, then it is Int32. You need to use the Convert class:

long l = Convert.ToInt64(selectCommand.ExecuteScalar());

If you're thinking that your counts are going to overflow an int/Int32, you ought to use COUNT_BIG() in your SQL instead - it has the correct return type.


As to why the casts aren't working, I'm not sure. The following C#:

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
long lCount = (long)cmd.ExecuteScalar();
Int64 iCount = (Int64)cmd.ExecuteScalar();

Compiles to this IL:

L_0000: nop 
L_0001: newobj instance void [System.Data]System.Data.SqlClient.SqlCommand::.ctor()
L_0006: stloc.0 
L_0007: ldloc.0 
L_0008: callvirt instance object [System.Data]System.Data.Common.DbCommand::ExecuteScalar()
L_000d: unbox.any int64
L_0012: stloc.1 
L_0013: ldloc.0 
L_0014: callvirt instance object [System.Data]System.Data.Common.DbCommand::ExecuteScalar()
L_0019: unbox.any int64
L_001e: stloc.2 
L_001f: ret 

That is, they appear to compile to identical code.