C# Variables Types


Introduction

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. We have different types of variables available in C#.

Variable Types

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

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. We cannot access this variable outside the method. Let's have a look into below code example.

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

In above example, we have declared a varible "localVar". We declared inside a method, we cannot access this variable outside the method.

Global Variables

Declared outside the method which can be accessible by other methods as well. Unlike a local variable declaration, we are declaring a variable outside the method so other method can also access the same.

public class MyClass 
{ 
    int globalVar = 10; // global variable 

    // Method-1
    void Method1() 
    { 
        Console.WriteLine(globalVar); // accessible here 
    } 

    // Method-2
    void Method2() 
    { 
        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;