Andrew Andrew - 5 months ago 15
C# Question

Is it possible to create LOCAL property("active variable") in c#?

As example, there is possible to make "active" global variable(property) "Area" with auto-calculation:

public int Width = 5;
public int Length = 10;
public int Area
get{ return Width * Length;}

But... is there is possible to make something like this but inside of a method -- local var?


The term for Area in your example is a property. Properties can only be declared in classes/structures.

However, you can accomplish something similar with a lambda (a special syntax that declares a function that can capture variables contextually):

void Method()
    int width = 4;
    int length = 2;
    Func<int> area = () => length * width;
    Console.WriteLine("{0}", area());  // 8
    length = 3;
    Console.WriteLine("{0}", area());  // 12