The objective of this article and youtube video is to familiarize you with the C# variables. How to declare and initialize C# variables, variables naming rules, definite assignment policy, implicitly typed local variables, and much more. In any programming language, a variable is one of the primary methods for moving information around.
In this tutorial, you’ll learn:
C# variable is something you want the computer to remember while your program is running. Computer programs need places to store and process this information while working with it. These places are called variables because the information stored there can change, or vary, during program execution. Variables are considered the primary method for moving information around.
Note: C# variables are case-sensitive.
- According to the dictionary, a variable is anything that is not consistent.
- “Variable” is the name given to a computer memory location for storing data that can be reused throughout the program—that is, it is used to store, retrieve, and modify changeable data.
- A variable is always defined by a datatype, which means that it will hold the value of a specific type, such as string, int, float, and so on.
- A value must be assigned to a variable before using it to avoid a compile-time error.
You can’t just choose any sequence of characters as a variable name. Instead, C# has some rules regarding variable names that should be followed:
- camelCase for local variables, such as cost, orderDetail, dateOfBirth, and firstName
- A meaningful or descriptive name that is neither too long nor too short to identify the information stored in a variable just by looking at it
- Can contain the letters a–z and A–Z, the numbers 0–9, and the underscore (_) character—other symbols are not allowed
- No spaces and cannot start with a number
- Cannot use a word reserved by C# language—keywords such as namespace, class, using, and so on
You can name a variable like a keyword by adding a prefix to the name: the at symbol (@).
Example: @namespace, @class, @using, etc.
- cost, name, order, order1, _order1, income
- order_Detail, orderDetail, dateOfBirth, hourlyRate, firstName, first_Name, isValid
- 1 (number)
- class, while, if, protected (keyword)
- 1order, 1name (starts with a number)
Create a variable by declaring its type and then giving it a name using the syntax below.
Variable Declaration and Initialization Syntax Using Two Statements
When you declare a variable, the computer knows that it has to reserve a place in its memory for this variable.
datatype variableName; // declaration syntax
To initialize a variable, you need to assign it a value. This is done by naming the variable followed by an equal sign (=) and then the value.
variableName = variableValue; // initialization syntax
Note: The term initialize means to assign an initial value.
Variable Declaration and Initialization Syntax Combined on a Single Line
While you can declare a variable and assign it a value in two separate steps, it is also possible to do both of them at the same time on a single line:
datatype variableName = variableValue; // syntax
Here, datatype must be one of the valid data types, and variableName is the identifier used for the variable. This is an explicitly typed local variable where the type is explicitly defined.
string name; int age; int weight; bool isMarried;
You can declare multiple variables on one line in the same C# statement by specifying them in the form of a comma-separated “,” list if they are of the same type.
int age, weight; // OR int age, Weight;
Use semicolon (;)-separated C# definition statements if they are of different types.
string name; int age, weight; bool isMarried = true;
C# enforces a definite assignment policy. This means that you will need to initialize the local variable with the value before using it. Suppose the following is written:
Console.WriteLine(name); //Error : Use of unassigned local variable 'name'
Error: Use of unassigned local variable ‘name’
If you try to use a variable that hasn’t been declared, your code won’t compile. In this case, the compiler will tell you that something is wrong. Trying to use a variable without assigning it a value also causes an error.
In order to initialize the variable with a value, you simply have to use the assignment operator “=”. The variable name is on the left side of the operator and on the right side is the value in the following manner.
name = "Pirzada"; age = 35; weight = 70; isMarried = true;
Once a variable has been declared with a type, it cannot be redeclared with a new type, and it cannot be assigned a value that is not compatible with its declared type. For example, you cannot declare an int and then assign it a Boolean value of True/False.
age = true; //Error : Cannot implicitly convert type 'bool' to 'int'
Error: Cannot implicitly convert type ‘bool’ to ‘int’
If I try to assign a string to an age variable, it is declared an int datatype.
age = "Pirzada"; // OR age = name;
The above statement will give a compile-time error because string variable value cannot be assigned to an int type variable.
You can combine the declaration and initialization statements at the same time on the same line as shown below, which is more convenient.
string name = "Pirzada"; int age = 35; int weight = 70; bool isMarried = true;
You can also use a mathematical expression.
int wowExp = (3 + 2) * 4; //Print Value Console.WriteLine(wowExp); // 20
The right side is being evaluated and then assigned to the variable on the left. Meaning
5 * 4 is
20, which will be assigned to the
Use of variables in the mathematical expression.
int a, b, c; a = 3; b = 2; c = 4; int wowExp = (a + b) * c; //Print Value Console.WriteLine(wowExp); // 20
You can also assign the same value to multiple different variables all at the same time.
//assign multiple variables at once int a, b, c; a = b = c = 786; //Print Values Console.WriteLine(a); // 786 Console.WriteLine(b); // 786 Console.WriteLine(c); // 786
C# 3.0 introduced the implicitly typed local variables with the var keyword. Now you can declare a variable without giving an explicit or real type. The variable still receives a type at compile-time, but the type is provided by the compiler.
The var keyword in c# instructs the compiler to infer the type of a variable from the expression on the right side of the initialization statement. It just means that the compiler determines and assigns the most appropriate type.
var variableName = variableValue; // Syntax
var is optional, and it’s just for convenience.
Let’s use the same variables as above.
var name = "Pirzada"; var age = 35; var weight = 70; var isMarried = true;
Now the variables are implicitly typed local variables, meaning that you don’t have to explicitly specify the type. The compiler determines and assigns the most appropriate type. Double quotes indicate a string variable, single quotes indicate a char variable, and the true and false values indicate a bool type.
Suggestion: Using var is convenient, but use it only when the type is obvious from the right side of the assignment.
A literal number with a decimal point is inferred as double unless you add the M/m suffix to indicate a decimal variable or the F/f suffix to indicate float variable.
var income = 24899.45m; var hourlyRate = 20.8f; //Print Type Console.WriteLine(income.GetType()); Console.WriteLine(hourlyRate.GetType()); //Print Values Console.WriteLine(income); Console.WriteLine(hourlyRate);
hourlyRate, you need to add
f as a suffix after
20.8 to explicitly tell the compiler to change
20.8 to a float. Similarly, to initialize
income, you need to add
m as a suffix to change
24899.45 into a decimal type.
A few rules you need to follow:
- C# var can only be declared and initialized in a single statement. Otherwise, the compiler doesn’t have anything from which to infer the type.
- var cannot be used on fields at class scope.
- The initializer cannot be null and must be an expression.
- Multiple, implicitly typed variables cannot be initialized in the same statement.
- You can’t set the initializer to an object unless you create a new object in the initializer.
There are two kinds of types in C#: value types and reference types.
Variables of value types directly contain their data, whereas variables of reference types store references to their data, the latter being known as objects.
With reference types, it is possible for two variables to reference the same object and, therefore, possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other (except in the case of ref and out parameter variables).
First letter of the first word is lowercase, while the first letter of every subsequent word is uppercase.
Example: firstName, lastName, fullName, isValid.
Identifiers are names used to determine classes, functions, variables, or any item defined by the programmer.
C# Local variables
Local variables are declared inside methods and they only exist during the call to that method. Once the method returns, the memory allocated to any local variables is released.
A declaration statement declares a new variable and ends with a semicolon.
The compiler determines and assigns the most appropriate type.
💬 What other C# Variables topics should I cover here?
Please use twitter to share your suggestions. We will add your feedback here.
Share With Love ❤️
C# Reference | Microsoft Docs
- C# Variable
- implicitly typed variable
- default literal
- new Operator
- Default value