Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain local variable across method calls

Tags:

c#

Is there a way in C# to have a method retain a variable across different calls? For example:

private void foo()
{
    int j; //declare this so as it isn't destroyed with the stack frame.
    int i = calculateSomeValue() + j;
    j = i;
}

The normal way I would do this would be with a member variable like this:

private int j = 0;
private void foo()
{
    int i = calculateSomeValue() + j;
    j = i;
}

I don't like how the variable j can be accessed in all of the other methods of the class. Plus it just seems messy this way: defining a member variable when it will only be used in one method to keep track of the value of i when the method was last called.

Is this possible in a nice/clean way? Or should I just use the member variable way and forget about it?

like image 984
Danny Herbert Avatar asked May 15 '26 00:05

Danny Herbert


2 Answers

You could use a tiny little nested class to encapsulate it, along these lines:

public class Test
{
    private int foo()
    {
        return nested.foo();
    }

    private int calculateSomeValue()
    {
        return 42;
    }

    readonly Nested nested = new Nested();

    private class Nested
    {
        private int j;

        public int foo()
        {
            int i = calculateSomeValue() + j;
            j = i;
        }
    }
}

The methods in the outer class will only be able to access the public members of Nested, so they can only access foo() in this example - j is inaccessible. But note that methods in Nested have access to all the private members of the outer class.

like image 53
Matthew Watson Avatar answered May 17 '26 14:05

Matthew Watson


I don't think there is another way of giving the scope you ask. The fact that other methods can access j in this case being a member variable is a direct consequence of the OOP concepts your are using encapsulating the members inside the holder object.

So I would continue using the member variable and don't worry about other methods being able to access it. If for some reason you must avoid other methods accessing the variable, maybe you should consider refactoring in its own type although maybe with the example given is not justified.

Hope this helps.

like image 24
Karel Tamayo Avatar answered May 17 '26 14:05

Karel Tamayo