English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In C#, variables contain data values of specific data types.
Syntax
<data type> <variable name> = <value>;
The following declares and initializes an int type variable.
int num = 100;
Above, int is the data type, num is the variable name (identifier). The = operator is used to assign a value to a variable. The value on the right side of the = operator is the value assigned to the variable on the left. In the above example, the value of 0 is assigned to the variable num.100 assigned to the variable num.
The following statements declare and initialize variables of different data types.
int num = 100; float rate = 10.2f; decimal amount = 100.50M; char code = 'C'; bool isValid = true; string name = "Steve";
The following are the naming conventions for declaring variables in C#:
Variable names must be unique.
Variable names can only contain letters, numbers, and underscores _.
Variable names must start with a letter.
Variable names are case-sensitive, num and Num are considered different names.
Variable names cannot contain reserved keywords. If you want to use a reserved keyword as an identifier, you must add the @ prefix before the keyword .
C# is a strongly typed language. This means you can assign values of specified data types. You cannot assign an integer value to a string type, and vice versa.
int num = "Steve";
Variables can be declared first and then initialized.
int num; num = 100;
A value must be assigned to a variable before it is used; otherwise, C# will give a compile-time error.
int i; int j = i; //Compile-time error: Use of uninitialized local variable “ i”
The value of a variable can be changed at any time after initialization.
int num = 100; num = 200; Console.WriteLine(num); //Output:200
Multiple variables of the same data type can be declared and initialized in the same line, separated by commas.
int i, j = 10, k = 100;
Multiple variables of the same type can also be declared in multiple lines, separated by commas. The compiler will treat it as a single statement until a semicolon is encountered;.
int i = 0, j = 10, k = 100;
You can assign the value of a variable to another variable of the same data type. However, you must assign a value to it before using the variable.
int i = 100; int j = i; // The value of j is100
In C#, variables are classified based on how they are stored in memory. Variables can be value types, reference types, or pointer types.
You do not have to specify a specific type when declaring variables. Use the var keyword instead of a data type. Learn about it next.