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

Time:09-23

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 ...

CodePudding user response:

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

CodePudding user response:

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