C# Tutorials
C# Methods
C# Classes
C# Examples
Variables are data storage containers.
In C #, there are different types of variables (defined by different keywords), for example:
To create a variable, you must specify a type and assign a value:
"type variableName"
=
"value"
;
Where type is type C# (like int or string), and variableName is a variable name (such as x or name).
The equal symbol is used for variable values
To create an alternative that should keep the text, see the following example:
Make a variable called name of type string and assign it the value "John":
string
"name"
=
"John"
;
"Console"
.
WriteLine
(
"name"
)
;
To create an alternative that should keep the number, see the following example:
Make a variable called myNum of type int and assign it the value 15:
int
"myNum"
=
15
;
"Console"
.
WriteLine
(
"myNum"
)
;
You can also declare the variable without giving value, and provide value later:
int
"myNum"
;
"myNum"
=
15
;
"Console"
.
WriteLine
(
"myNum"
)
;
Note that if you assign a new value to an existing variant, it will delete the previous value:
Change myNum value to 20:
int
"myNum"
=
15;
"myNum"
=
20
; // myNum is now 20
"Console"
.
WriteLine
(
"myNum"
)
;
However, you can add a keyword const if you do not want others (or you yourself) to write over existing values (this will declare the variable as "continuous", meaning that it cannot be changed and read only):
const
int
"myNum"
=
15
;
"myNum"
=
20
; // error
Demonstration of how to advertise variable in other genres:
int
"myNum"
=
5
;
double
"myDoubleNum"
=
5.99
"D"
;
char
"myLetter"
=
'D'
;
bool
"myBool"
=
true
;
string
"myText"
=
"Hello"
;
The WriteLine() method is often used to display variable values in the console window.
To combine both text and variable, use the + character:
string
"name"
=
"John"
;
"Console"
.
WriteLine
(
"Hello " +
"name"
)
;
You can also use the character + to add variables to other variables:
string
"firstName"
=
"John "
;
string
"lastName"
=
"Doe"
;
string
"fullName"
= "firstName"
+ "lastName"
;
"Console"
.
WriteLine
(
"fullName"
)
;
In numerical values, the character + acts as a mathematical operator (note that we use int (integer) variables here):
int
"x"
=
5
;
int
"y"
=
6
;
"Console"
.
WriteLine
(
"x"
+
"y"
)
; // Print the value of x + y
In the example above, you can expect:
To declare more than one variable of the same type, use a comma-separated list:
int
"x"
=
5
,
"y"
=
6
,
"z"
=
50
;
Console
.
WriteLine
(
"x"
+
"y"
+
"z"
)
;
All C# variables must be identified by different names.
These unique names are called identifiers.
Identifiers can be short words (such as x and y) or multiple descriptive words (age, total, volume).
Note: It is recommended to use descriptive words to create understandable and sustainable code:
// Good
int
"minutesPerHour"
=
60
;
"// OK, but not so easy to understand what" m
"actually is"
int
"m"
=
60
;
The general rules for naming variables are: