A matter of scopes (method paramaters versus class properties)

Defining variable names must be done carefully sometimes to prevent logical errors in your code. Just to provide and example of where things can go wrong you can see the following snippet.


public class TestClass
        public int Variable { get { return -1; } }
        private int _variable1;
        private int _variable2;
        public TestClass(int Variable)
            _variable1 = Variable;
            _variable2 = this.Variable;

        public override string ToString()
            return "Value of variable1: \{_variable1}\{Environment.NewLine}Value of variable2: \{_variable2}";


This example is pretty straightforward and easy to correct, but can be harder to detect in a larger code base.


But the lesson is to be careful when naming your variables to ensure that you know exactly what variables are used at which times.

In the above example the method parameter is more locally scoped and is thus prioritized rather then the class property. And in order to use the class property you need in this case to use the "this" keyword.

Comments are closed