Friday, October 25, 2024

C# Can you declare a static variable inside a method?

When you declare a variable inside method in C#, then such variable is called local variable. The question is: can you declare a static variable inside a method in C#? In other words, can static local variable be defined in C#?

In C#, you cannot declare a static variable directly inside a method. Static variables belong to the class, not to a specific instance or method.

However, you can declare a static variable at the class level (outside of any method) and access it within a method. Here's an example:

public class MyClass
{
    // Static variable at the class level
    private static int staticVariable = 0;

    public void MyMethod()
    {
        staticVariable++;
        Console.WriteLine("Static variable value: " + staticVariable);
    }
}
In this example, staticVariable is a static variable that belongs to the class MyClass. It can be accessed and modified within the MyMethod method and retains its value across different method calls.

No comments:

Post a Comment

Hot Topics