What am I supposed to use when handling a value in C#, which is bigint for an SQL Server database?
12 Answers
That corresponds to the long (or Int64), a 64-bit integer.
Although if the number from the database happens to be small enough, and you accidentally use an Int32, etc., you'll be fine. But the Int64 will definitely hold it.
And the error you get if you use something smaller and the full size is needed? A stack overflow! Yay!

- 30,738
- 21
- 105
- 131

- 22,995
- 5
- 52
- 66
-
122Sure it's not integer overflow? – luqui Aug 09 '12 at 16:38
-
11Good reference for more data types: http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx – JustBeingHelpful Aug 17 '12 at 14:47
-
6in C#, `long` is not capitalized. – Shawn Kovac Mar 16 '14 at 16:23
I just had a script that returned the primary key of an insert and used a
SELECT @@identity
on my bigint primary key, and I get a cast error using long - that was why I started this search. The correct answer, at least in my case, is that the type returned by that select is NUMERIC which equates to a decimal type. Using a long will cause a cast exception.
This is one reason to check your answers in more than one Google search (or even on Stack Overflow!).
To quote a database administrator who helped me out:
... 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.
We don't often notice since the printed value looks the same.

- 9,564
- 146
- 81
- 122

- 157
- 1
- 2
-
-
10You got a cast error because SCOPE_IDENTITY and @@IDENTITY return NUMERIC(38, 0), not because your BigInt PK does not fit into a C# Int64. In other words, BigInt _is_ the same as Int64, but BigInt values returned through SCOPE_IDENTITY or @@IDENTITY may be up-converted to NUMERIC(38, 0). – Dan Hermann Jan 05 '14 at 13:21
-
Thanks Dan. FYI, still happening with SQL Azure (RTM) - 12.0.2000.8 & .NET v 4.5 – Gunnar Sep 11 '15 at 17:31
-
1Surprised to see no comment to Dan's correction about the type for SQL Server identity values to just use the following on the DB side: SELECT CAST(@@IDENTITY as BIGINT) as IdentityINT64 – dmarietta Dec 15 '22 at 18:34
You can use long
type or Int64
I managed to convert the (bigint) value returned from the DB using Convert.ToInt64.
ie
var Id = Convert.ToInt64(identityAsTable.Rows[0].Field<object>(0));

- 613
- 5
- 6
I was handling a bigint datatype to be shown in a DataGridView and made it like this
something = (int)(Int64)data_reader[0];

- 98,673
- 67
- 256
- 322

- 1