C# Variable
A variable is used to store data to a memory location. It thus specifies the name of the memory location. As the name itself suggests, the value of a variable can vary and thus can be reused multiple times. To easily identify a memory location, it represents a memory location through a symbol.
C# basic variable types:
Variable Type | Example |
Decimal | decimal |
Boolean | true or false value |
Integral | int, char, byte, short, long data types |
Floating point | float and double data types |
Nullable | Nullable data types |
Syntax: To declare a variable.
type variable_list;
Example 1: To declare a variable.
int a, b; double c; float d; char ch; |
Explanation:
In the above example, a, b, c, d, and ch are variables and int, double, float, and char are data types.
Example 2:
int a=5; float b=5.1, c = 10.2; char ch='Z'; |
Explanation:
In the above example, we are declaring a variable and are also providing values while declaration.
Rules for defining variables:
A variable can
- Have alphabets, digits, and underscores.
- Have a name starting with an alphabet and underscore only.
- Not have a name starting with a digit.
- Not have a white space within the name.
- Not have the name of any reserved word or keyword e.g. int, float, etc.
Valid variable names:
float a; float _a; float a10;
Invalid variable names:
float 5; float a b; float int;