C# variable is just a name of storage area which our program can manipulate as per requirement. Variables are of specific type which determines how much memmory it will occupy and type of value to be stored.

The basic value types are categoriesed as below table

Type Example
Integral types sbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating point types float and double
Decimal types decimal
Boolean types true or false values
Nullable types Nullable data types

C# also allows us to define other types of variable such as enum and reference type of variable such as class

C# suports declaring different types of value with different keyword, for example :

int - which stores whole numbers, it can be positive or negative like 333 or -340
double - which stores floating point number, it also can be positive or negative like 3.14 or -3.14
char - which stores single characters, it always enclosed by single quotes like 't' or 'T'
string - which stores big string, which always enclosed by double quotes like "Tutorials Corner"
bool - which stores either true or false


type nameofvar = value;

Let's see some examples of declaring a varialbe of different type and initialise them with intial value, For example

int year = 2020;
double percentage = 90.01;
char initialLetter = 'T';
string fullName = "Tutorials Corner";
bool isGood = true;

Console.WriteLine("Value of integer variable is:" + year);
Console.WriteLine("Value of double variable is:" + percentage);
Console.WriteLine("Value of char variable is:" + initialLetter);
Console.WriteLine("Value of string variable is:" + fullName);
Console.WriteLine("Value of bool variable is:" + isGood);

Above code will print the output as below

Value of integer variable is:2020
Value of double variable is:90.01
Value of char variable is:T
Value of string variable is:Tutorials Corner
Value of bool variable is:True

It's not necessary to declare a variable and assign value directly to it, you can also assign the value later. If you reassign value to variable then it will overwrite the value of variable. If you want to declare fixed value for variable then declare as const variable. Once variable is declared with const keyword then it will be of constant and unchangable and readonly. When you declare a const variable you must have to provide a value of variable else it will throw compile time error.

There are some naming conventions while declaring variable in C# as below

  • Variable names must be a unique through the scope.
  • It can contains letter (small/big, digits and underscore only.
  • It can always starts with a letter or underscore
  • It can never have a space and special characters
  • It can't be start with special characters
  • It can't be same as reserved keywords like int, class, public etc

Note: Variable names are case-sensitive, it means fullName and FullName both are treated as different variables.


← Previous

Next →