Containers for storing data values are Variables. The different types of variables are as follows:
- int- it stores the integers (whole numbers) without decimals. Ex. 245, -678
- double- it stores the floating point numbers, with decimals. For ex. 18.25 or -18.25. Upto 15 digit decimal point will be executed.
- char- stores single characters, such as ‘b’ or ‘C’. However, it can also be surrounded by double quotes.
- string – it usually stores text, such as “ Hello World”. These values are surrounded by double quotes.
- bool- values are stored with two states either true(1) or false(0).
Declaring or Creating Variables
To create a variable, its type should be specified and value should be assigned.
Syntax: type variableName = value;
where type is C# type( such as int or string), and variableName is name of variable( such as b or name). Equal sign is used to assign values to the variable.
string name = “FindAndSolve”;
The const keyword is useful for always storing same value, so our code won’t get messed up. Example: PI(3.1415…).
const int myNum = 124;
myNum = 1347; // error
Note: A constant variable cannot be declared without assigning a value. Otherwise, an error will occur.
WriteLine() method is used to display values of variable to console window. To combine both text and variable, + character should be used.
string name = "FindAndSolve";
Console.WriteLine("Hello " + name);
You can also use the + character to add a variable to another variable:
string firstName = "FindAndSolve";
string lastName = "Online Tutorial";
string fullName = firstName + lastName;
FindAndSolve Online Tutorial
For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here):
int x = 10;
int y = 7;
Console.WriteLine(x + y); // Print the value of x + y
From the example above, you can expect:
- x stores the value 10
- y stores the value 7
- Then we use the WriteLine() method to display the value of x + y, which is 17.
Declaring Many Variables
To declare more than one variable of the same type, use a comma-separated list:
int x = 7, y = 8, z = 15;
Console.WriteLine(x + y + z);
All C# variables must be identified with unique names called identifiers. It can be short names ( a and b) or more descriptive names( age, sum, totalVolume).
Note: To create the code which is understand and maintained, it is recommended to use descriptive names.
// Good int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is int m = 60;
General rules for naming variables:
- Names contain digits, letters, underscore character(_)
- Must begin with a letter.
- Should start with a lowercase letter and cannot contain whitespace.
- These are case sensitive(“myVar” and “myvar” are different variables)
- Reserved words ( like C# keywords, such as int or double) can’t be used as names.