Data types in C#

A data type specifies the size and type of variable values.

It is important to use It is important to use the correct data type for the corresponding variable so the system knows how much memory to allocate for a variable; this helps avoid errors and save time and memory.

Numbers

Integer types

The int data type can store whole numbers from -2147483648 to 2147483647.

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that the value should end with an “L”

Floating point types

We use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.

The float and double data types can store fractional numbers.

The difference: float has a precision of 6 or 7 decimal digits, while double has a precision of 15 decimal digits.

A floating point number can also be a scientific number with an “e” to indicate the power of 10.

Booleans

A boolean data type is declared with the bool keyword and it’s value can only be either true or false:

bool isTheCarRed = true;
bool isTheCarBlue = false;
Console.WriteLine(isTheCarRed); // Outputs True
Console.WriteLine(isTheCarBlue); // Outputs False

Characters

The data type used to store a single character is char. The character has to be surrounded by single quotes:

char myGrade = ‘A’;

Strings

The data type used to store a sequence of characters is string. The string has to be surrounded by  quotes:

string greeting = “Hello World!”;

Exercise

Declare your name, age and height (in cm) and whether you like Maths or not, with the appropriate data types and print them out on separate lines.