C# Data Types
C# Data Types are predefined datatypes in C# used for storing the most basic type of data. This includes datatypes for storing numbers, characters, strings, and boolean values. They are called primitive data types in other languages because you use them to build complex types such as classes and structures. C# Data Types contain a clearly defined set of values and can store a fixed range of data. They are the fundamental building blocks of your application.
Each C# Data Types is mapped to a .NET type thanks to .NET’s Common Type System. It maps data types from different languages into a single .NET type. For example if you use the int data type, you are actually using the .NET type System.Int32. Visual Basic’s Integerdata type is also mapped to System.Int32 as well.
The following table shows some of the available C# Data Types that you can use for storing numbers.
|Type||.NET Type||Value Range|
|sbyte||System.SByte||Integer between -128 and 127|
|byte||System.Byte||Integer between 0 and 255|
|short||System.Int16||Integer between -32768 and 32767|
|ushort||System.UInt16||Integer between 0 and 65535|
|int||System.Int32||Integer between -2147483648 and 2147483647|
|uint||System.UInt32||Integer between 0 and 4294967295|
|long||System.Int64||Integer between -9223372036854775808
|ulong||System.UInt64||Integer between 0 and 18446744073709551615|
You might notice the u at the beginning of some data types such as ushort. It means that the number it will store is “unsigned” and you can only store positive numbers(and 0) in them. They store larger values as a reward for forbidding negative values. Note that byte is the unsigned version of sbyte but it was not named usbyte.
The next table shows C# Data Types that can store “floating numbers” or numbers with a fractional part or decimal points such as 1.5.
|Type||.NET Type||Approximate Range||Precission|
|float||System.Single||±1.5E-45 to ±3.4E38||7 digits|
|double||System.Double||±5.0E-324 to ±1.7E308||15 – 16 digits|
|decimal||System.Decimal||(-7.9 x 1028) / (100 to 28) to
(7.9 x 1028) / (100 to 28)
|28 – 29 significant digits|
We used the shorthand version of scientific notations. Instead of writing 1.5 x 10-45, we wrote 1.5E-45 instead.
There are other types of C# Data Types which are used for storing non-numerical data.
|Type||.NET Type||Allowed Values|
|char||System.Char||Single Unicode character, stored as an integer between 0 and 65535|
|bool||System.Boolean||true or false|
|string||System.String||A sequence of characters|
The char datatype is used for storing single Unicode character. Characters must be enclosed by a pair of single quotation marks (‘a’). The bool datatype can store true or false which is used mostly when making decisions in a program. The string is used for storing a sequence of characters such as a message. Values stored in string must be wrapped between quotation marks (“message”) so it can be distinguished as a string by the compiler.