Junior
What is scope in C#?
sobes.tech AI
Answer from AI
The scope in C# defines the accessibility of variables, methods, and types within a certain part of the program. It restricts where in the code a particular identifier can be used.
Main scopes:
- Block Scope: Variables declared inside curly braces
{ }are only accessible within that block. - Method Scope: Variables and parameters declared inside a method are only accessible within that method.
- Class/Struct Scope: Members of a class or struct (fields, properties, methods) are accessible depending on access modifiers (public, private, protected, internal).
- Namespace Scope: Types declared within a namespace are accessible within that namespace and other namespaces where
usingis used. - Assembly Scope: Types with the
internalmodifier are only accessible within the current assembly.
Example of block scope:
public void ExampleMethod()
{
int x = 10; // x is only accessible inside ExampleMethod
if (x > 5)
{
int y = 20; // y is only accessible inside the if block
Console.WriteLine(y);
}
// Console.WriteLine(y); // Compilation error: y is not accessible here
}