C Sharp (C#) Data Types


In C Sharp, every thing needs to be assigned a data type. It is a strong typed language. Which means all values, variables, expressions are associated with a certain Data Type. Considering a variable to be a container for holding data, a Data Type is responsible for determining what type of data could be held by the variable.
For example, if a number needs to be stored in a variable, then the variable should be declared as a Data Type that can hold a number. Similarly, if a string needs to be stored in a variable, the variable needs to be set to a data type that can hold the string.
The Data types lets the variables to hold any type of data making C sharp suitable to create wide variety of dot net applications.
On a high level, the Data Types are classified into Two Types : Value Types and Reference Types
Value Types – These data types hold the actual value. (Ex : 1.2, 22/7)
Reference Types – These data types hold the reference to the actual value. Meaning, these data types stores the address where the value is stored. Lets suppose the value is “hello” and is stored at a memory location 0x123. When a variable is declared as a Reference Type, instead of storing “hello” value in the variable, the address (0x123) of the value is stored.
Each data type in C Sharp is designed to hold a specific type of data and for a specific range of data. The data type is same in all the supported .NET languages. So the “int” in C# is same as int in any other programming language that .NET supports.
There are signed and unsigned data types in C Sharp. For any of the data types either signed or unsigned, the range of values always remains the same but the max and min values change. For example, if a data type has a range of 400 numbers, the signed range will be from –200 to +199. The unsigned range will be from 0 to 400.
How to choose what type of data type to use:
First, identify what type of data needs to be stored. Is it a string or a number or a character or a true/false value.
Second, what is the range of numbers that you want to save. What could be the possible max and min value that you want to save.
Type(Click on each type) Size (in bits) Range Used For
bool 8 true / false
byte 8 0 - 255 8 bit unsigned integer
char 16 0 - 65535 16 bit unsigned integer
decimal 128 1E–28 to 7.9E+28 128 bit signed integer
double 64 5E–324 to 1.7E+308 64 bit decimal values
float 32 1.5E–45 to 3.4E+38 decimal values
int 32 –2,147,483,648 to 2,147,483,647 Integers
long 64 -9223372036854775808 to 9223372036854775807 64 bit signed Integers
sbyte 8 127 to 128 8 bit signed integer
short 16 –32,768 to 32,767 Short Integers
uint 32 0 to 4,294,967,295 Unsigned Integers
ulong 64 0 to 18446744073709551615 64 bit unsigned Integers
ushort 16 0 to 65,535 Unsigned Short Integers

No comments: