Easy Differences between Local Variable and Class Variable
Let us find out the top 5 differences between class variables and local variables based on their functionality and usage and summarize with examples.
class MyClass2
{
private static int _counter = 0;
public MyClass2()
{
if (_counter > 2)
{
throw new Exception("Instances created beyond limit");
}
else
{
++_counter;
}
}
public void ShowCounter()
{
Console.WriteLine($"Counter is at {_counter}");
}
}
MyClass2 c;
for (int i = 0; i < 5; i++)
{
c = new MyClass2();
c.ShowCounter();
}
output:
Counter is at 1
Counter is at 2
Counter is at 3
Unhandled exception. System.Exception: Instances created beyond limit