Data Types in C#

There are some really good descriptions and explanations concerning data types on the internet. However I will add my understanding and comments about them on this website. Just in case you stumble across this page in your search for ultimate C# knowledge.  There are 2 data types. Value Types and Reference Types. I published a training video that discusses these and the relation they have with the Stack and the Heap. Check it out here.

The trigger that prompted me to write this article is because I was searching for the differences between the numeric Value Types. I was a little confused about the difference between a decimal, integer, float, double, long, , etc… So I thought I’d write it down. I learn best when I write things down. All of your numeric data types are value types (watch my video, if a value type is part of class then they are still value types, but are stored like reference types). As well, a Boolean, enum and struct are value types too. So in my quest to decide which numeric data type to use in which situation I discovered this table. Using it, I can take my current requirements into consideration and use the appropriate one.

C# Type .Net Framework Signed? Possible Values
sbyte System.Sbyte Yes -128 to 127
short System.Int16 Yes -32768 to 32767
int System.Int32 Yes -2147483648 to 2147483647
long System.Int64 Yes -9223372036854775808 to 9223372036854775807
byte System.Byte No 0 to 255
ushort System.Uint16 No 0 to 65535
uint System.Uint32 No 0 to 4294967295
ulong System.Uint64 No 0 to 18446744073709551615
float System.Single Yes ~ ±1.5 x 10-45 to ±3.4 x 1038 with 7 figures
double System.Double Yes ~ ±5.0 x 10-324 to ±1.7 x 10308 with 15 or 16 figures
decimal System.Decimal Yes ~ ±1.0 x 10-28 to ±7.9 x 1028 with 28 or 29 figures
char System.Chat N/A Any Unicode character (16 bit)
bool System.Boolean N/A true or false

If you decide to use a short variable, take note that if the number exceeds 32767 an exception will happen. The trigger I referred to above was also mostly focused on fractional numbers. I.e. numbers to the right of the decimal point. Therefore I was and am very interested in explaining the difference between a float, double and a decimal.

As you can see from the table able a float is signed, meaning it can be positive or negative and will provide us with 7 numeric values to the right of the decimal point. A double is an exponentially larger value than the float and the decimal and will provide us with 15-16 numeric values to right of the decimal point. The decimal, provides us with the largest number of significant figures, being 28-29. Therefore, if you are after the greatest amount of numeric values to the right of the decimal, then use a decimal. However, the largest number can be stored into the double value type.

image




Leave a Comment

Your email address will not be published.