YouTip LogoYouTip

Csharp Variable Scope

-- Learn not just technology, but also dreams!

C# Tutorial

C# Tutorial C# Introduction C# Development Environment C# Program Structure C# Basic Syntax C# Data Types C# Type Conversion C# Variables C# Variable Scope C# Constants C# Operators C# Decision Making C# Loops C# Encapsulation C# Methods C# Nullable Types C# Arrays C# Strings C# Structs C# Enums C# Classes C# Inheritance C# Polymorphism C# Operator Overloading C# Interfaces C# Namespaces C# Preprocessor Directives C# Regular Expressions C# Exception Handling C# File I/O

C# Advanced Tutorials

C# Attributes C# Reflection C# Properties C# Indexers C# Delegates C# Events C# Collections C# Generics C# Anonymous Methods C# Unsafe Code C# Multithreading C# Language Quiz
C# Variables C# Constants

C# Variable Scope

In C#, the scope of a variable defines its visibility and lifetime.

The scope of a variable is typically determined by the code block defined by curly braces {}.

Here are some basic rules regarding C# variable scope:

Local Variables

Variables declared inside code blocks such as methods, loops, and conditional statements are local variables. They are only visible within the code block where they are declared.

Example

void MyMethod()
{
int localVar =10;// Local variable
// ...
}

// localVar Not visible here

Block-Level Scope

In C# 7 and later, block-level scope was introduced, meaning any block created with curly braces {} can define the scope of a variable.

Example

{
int blockVar =20;// Block scope
// ...
}

// blockVar Not visible here

Method Parameter Scope

Method parameters have their own scope and are visible throughout the entire method.

Example

void MyMethod(int parameter)
{
// parameter Visible throughout the entire method
// ...
}

Global Variables

Variables defined at the class member level are member variables, visible throughout the entire class. If defined at the namespace level, they are visible throughout the entire namespace.

Example

class MyClass
{
int memberVar =30;// Member variable, visible throughout the entire class
}

Static Variable Scope

Static variables are declared at the class level, but their scope is also limited to the class in which they are defined.

Example

class MyClass
{
static int staticVar =40;// Static variable, visible throughout the entire class
}

Loop Variable Scope

Loop variables declared in a for loop are visible within the loop body.

Example

for(int i =0; i <5; i++)
{
// i Visible within the loop body
}

// i Not visible here

Overall, variable scope helps manage the visibility and lifetime of variables, ensuring they are used within their valid range, and also helps prevent naming conflicts.

← Pandas CorrelationsFastapi Path Operation Depende β†’