Search code examples
c#sql-servertypesdatasetdataadapter

Why is SQL integral Numeric column mapped as System.Decimal in a C# DataSet?


Why is SQL integral numeric column (for example NUMERIC(3,0)) generated in C# (in DataSet as column type or in DataAdapter as parameter type) as type Decimal?

NUMERIC(3,0) can store integral values in range of -999 to 999. I think it should be in C# generated as type int or another integral one.

I think, this behavior is .NET or Visual Studio serious bug. How should I solve it, if I don't want rewrite generated code and I don't want to convert everywhere I use it between int and decimal? Thank you.


Solution

  • Your question is why MSSQL NUMERIC is converted to C# Decimal and the answer is because NUMERIC is still a floating point value even though you specify that it has no decimal places like NUMERIC[3,0].

    It would not make sense if NUMERIC where converted into C# into different types depending on whether or not you indicated it has any decimal points or not.

    I assume you are using NUMERIC[3,0] to save space in the database, but according to the docs, it uses 5 bytes. A SQL INT, on the other hand, only uses 4. And, even better, a SMALLINT uses only 2 bytes.

    Unfortunately, you're either going to have to convert your database to use SMALLINTs instead of NUMERIC or you're going to have to convert in your C#.

    It would be nice if you had only one entity that retrieved data from your database and then you could keep your conversions to a minimum and localized to a single location.