Question

How do I explicitly refer to the parameter as opposed to the member variable?

static recursive{

    public static List<string> output = new List<string>();

    public static void Recursive(List<string> output){
        ...
    }
}
Was it helpful?

Solution

An unqualified reference will always refer to the parameter because it is at a more local scope.

If you want to refer to the member variable, you need to qualify it with the name of the class (or this, for non-static member variables).

output = foo;              // refers to the parameter
recursive.output = foo;    // refers to a static member variable
this.output = foo;         // refers to a non-static member variable

But you should probably change the name anyway. It makes your code much easier to read.

And you shouldn't have public static variables at all. All of the .NET coding style guidelines strongly recommend properties instead of exposing public fields. And since those are always camel-cased, this problem solves itself.

OTHER TIPS

public static void Recursive(List<string> output){
        ...
    }

The code in the block that refers to output will always be local & not the member variable.

If you wish to refer to member variable, you could use recursive.output.

When you are inside the Recursive static method output will point to the argument of the method. If you want to point to the static field use the name of the static class as prefix: recursive.output

Give your member variable another name. The convention is to use Camelcasing on public static members.

public static List<string> Output = new List<string>();

public static void Recursive( List<string> output )
{
   Output = output;
}

You can explicitly reference recursive.output to indicate the static member, but it would be cleaner to rename either the parameter or the member.

I know of no way to explicitly refer to a parameter. The way this is usually handled is to give member variables a special prefix such as _ or m_ so that parameters will never have exactly the same name. The other way is to refer to member variables using this.var.

public class MyClass {
    public int number = 15;

    public void DoSomething(int number) {
        Console.WriteLine(this.number); // prints value of "MyClass.number"
        Console.WriteLine(number); // prints value of "number" parameter
    }
}

EDIT::

For static fields is required name of class instead of "this":

public class MyClass {
    public static int number = 15;

    public void DoSomething(int number) {
        Console.WriteLine(this.number); // prints value of "MyClass.number"
        Console.WriteLine(MyClass.number); // prints value of "number" parameter
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top