Value too big for long and bigint in C# and SQL Server

Viewed 76

Our entire application has been using a long to store large number values.

Like so:

public class SomeClass
{
    public long CardNumber { get; set; }
}

This is stored as a bigint in Microsoft SQL Server.

Now in order to account for a value larger than a long's max value I'm changing the datatype to a string and nvarchar in SQL Server (open to a better solution).

We don't seem to be doing much arithmetic with the value already across the application.

But we have code like this:

var someObj = new SomeClass();
someObj.CardNumber = 1234;

So I don't want to have to manually change it to

var someObj = new SomeClass();
someObj.CardNumber = 1234.ToString();

Across the application..

I was thinking of doing something like this..

public class SomeClass
{
    private long cardnum;

    public string CardNumber
    {
        get { return cardnum.ToString(); }
        set { cardnum = ConvertToLong(value); }
    }
}

but what if I then want to set the card number to a value larger than the long max value....as the convert to long would break in the setter

I'm a bit lost as to what I should do here ...

2 Answers

If 28 digits are enough, you could use a C# decimal. A SQL decimal has even a precision of 38 digits. C# long has only 18 digits ulong has 19.

An assignment like someObj.CardNumber = 1234; will continue to work without changes, as the int constant is automatically converted to decimal.

For numbers larger than Int32.MaxValue you must use a decimal constant with the decimal specifier m. someObj.CardNumber = 1234_5678_9012_3456_7890m;. You can also use decimal separators. They are not limited to blocks of 3.

Always encrypt sensitive data!

In SQL Server you could alter the BIGINT column to be of type NUMERIC. The maximum integer length available is NUMERIC(38, 0). One way to store NUMERIC(38, 0) in memory using C# would be to use the (native SQL Server type) SqlDecimal which is implemented as a Struct in System.Data.SqlTypes.

Related