C# Variable

Variables are the essential part of any application. In simple words, a variable is a memory location where an application can store the data. Variables can be used in different ways. We can use it to store the result of some calculation, we can use them to store the memory address etc.

In C# we must declare a variable before using it.

Following is the expression to declare a variable in C#.

datatype identifier;

For example

int i;
char ch;

The above statement declares a variable i of type int, and a variable named ch of type char.

Initializing Variables

After the declaration of a variable, we can assign the values to them using = operator like:

i = 10;
ch = 'a';  

We can also assign the values to variables while declaring them, for example :

int i = 10;
char ch = 'a';

Multiple variables can be declared on the same line also, but for that, all variables will be of the same data type, for example :

int i = 10, j = 20, k = 30;
char ch = 'a', ch1 = 'b', ch2 = 'c';

Remember: If a variable has been declared with a specific type, then we can not declare another variable with the same name of the same or different type. However, we can convert a variable of a particular type to another type using Implicit or Explicit conversions.

C# supports two kinds of variable types:

  1. Value types
  2. Reference types

Rules to declare variables in C#

  • A variable name can not start with a digit.
  • A variable name can not have space.
  • A variable name can only start with an alphabet or underscore.
  • We can not use reserved keywords like int,char, float etc as a variable name.
  • To declare variables of different types, we must use separate statements.

Below are the valid variable name declarations:

int _age = 10;
int _total1 = 150;
string name = "J Doe";
float Amount = 1.85F;

Below are the invalid variable name declarations:

int user age = 10; //Invalid name variable declaration. Variable name can not have space
int 1marks = 150; //Variable name can not start with a digit.
float double = 1.85F // Variable name can not be a reserved keyword;
int x = 10, bool y = true; //Different data types can't be used within a multiple-variable declaration

This was an overview and explanation of Variables in C#. Let's learn about the Constant Variables in C# in the next Section.