C# - Variables


In C#, Variables allows you to store and manipulate the data. They have a specific data type which defines the type of the information they can hold.

In C#, Variables can be categorized as:

Variable Name Description
Integer int, uint, long, ulong,byte, short and char
Float Float & doubles
Decimal decimals
Boolean True or False
Nullable Nullable value types

Declaring Variable

In C#, We can declare a Variable by specifying data type followed by the variable name.

int age; // Declaring an integer variable named 'age'

Initializing Variables

You can also declare and initialize a variable at the same time.

int age = 30; // Declaring and initializing 'age' with the value 30

Other Variable Types:

int myInt = 10;
float myFloat = 3.14f;
double myDouble = 2.718;

C# - Variable Scope

Local Variables

A variable that declared in a method, constructor or block which is accessible only withing that scope.

void MyMethod() 
{ 
    int localVar = 5; // local variable 
}

In above example, we can not use "int localVar" outside the "MyMethod".

Global Variables

Declared outside the method which can be accessible by other methods as well.

public class MyClass 
{ 
    int globalVar = 10; // global variable 
    void MyMethod() 
    { 
        Console.WriteLine(globalVar); // accessible here 
    } 
}
                                                

Constant Variables

Constant variables has fixed values and cannot be change during the runtime. You can define constant value by using ‘const’ keyword.

const int hoursInADay = 24;