C# Variables

In C#, a variable contains a data value of the specific data type.

<data type> <variable name> = <value>;

The following declares and initializes a variable of an int type.

Example: C# Variable
int num = 100;

Above, int is a data type, num is a variable name (identifier). The = operator is used to assign a value to a variable. The right side of the = operator is a value that will be assigned to left side variable. Above, 100 is assigned to a variable num.

The following declares and initializes variables of different data types.

Example: C# Variables
int num = 100;
float rate = 10.2f;
decimal amount = 100.50M;
char code = 'C';
bool isValid = true;
string name = "Steve";

The followings are naming conventions for declaring variables in C#:

  • Variable names must be unique.
  • Variable names can contain letters, digits, and the underscore _ only.
  • 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. Must prefix @ before keyword if want reserve keywords as identifiers.

C# is the strongly typed language. It means you can assign a value of the specified data type. You cannot assign an integer value to string type or vice-versa.

Example: Cannot assign string to int type variable
int num = "Steve";

Variables can be declared first and initialized later.

Example: Late Initialization
int num;
num = 100;

A variable must be assigned a value before using it, otherwise, C# will give a compile-time error.

Error: Invalid Assignment
int i;
int j = i; //compile-time error: Use of unassigned local variable 'i'

The value of a variable can be changed anytime after initializing it.

Example: C# Variable
int num = 100;
num = 200;
Console.WriteLine(num); //output: 200

Multiple variables of the same data type can be declared and initialized in a single line separated by commas.

Example: Multiple Variables in a Single Line
int i, j = 10, k = 100;

Multiple variables of the same type can also be declared in multiple lines separated by a comma. The compiler will consider it to be one statement until it encounters a semicolon ;.

Example: Multi-Line Declarations
int i = 0, 
    j = 10, 
    k = 100;

The value of a variable can be assigned to another variable of the same data type. However, a value must be assigned to a variable before using it.

Example: Variable Assignment
int i = 100;

int j = i; // value of j will be 100

In C#, variables are categorized based on how they store their value in memory. Variables can be value type or reference type or pointer type.

It is not necessary to specify the specific type when declaring variables. Use the var keyword instead of a data type. Learn about it next.

Learn C# using coding questions with answers and explanations.

C# Questions & Answers

Want to check how much you know C#?

Start C# Skill Test