int – stores integers (whole numbers), without decimals, such as 123 or -123
double – stores floating point numbers, with decimals, such as 19.99 or -19.99
char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
string – stores text, such as “Hello World”. String values are surrounded by double quotes
bool – stores values with two states: true or false.
Declaring (Creating) Variables
type variableName = value;
Where type is a C# type (such as int or string), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
Create a variable called name of type string and assign it the value “Vicky“:
string name = "Vicky";
Console.WriteLine(name);
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
Console.WriteLine(myNum);
Constants
The const keyword if you don’t want others (or yourself) to overwrite existing values (this will declare the variable as “constant”, which means unchangeable and read-only):
const int myNum = 15;
myNum = 20; // error
Other Types
int myNum = 5;
double myDoubleNum = 5.99D;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";
The const keyword is useful when you want a variable to always store the same value, so that others (or yourself) won’t mess up your code. An example is PI (3.14159…).
You cannot declare a constant variable without assigning the value. If you do, an error will occur: A const field requires a value to be provided.
Declare Many Variables
int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);
You can also assign the same value to multiple variables in one line
int x, y, z;
x = y = z = 50;
Console.WriteLine(x + y + z);