Blocking access to private member variables? Force use of public properties?

I'm using .NET 2.0 so do not have access to automatic properties. So I must resort to the following way of coding private variables and public properties

private string m_hello = null;

public string Hello
{
     get{return m_hello;}
     set{m_hello = value;}
}

For methods of the containing class of the above private/public members, is there anyway to restrict access to the private variable? I do not like that I can either use m_hello or Hello.

Thanks.


Solution 1:

As others have suggested this should be an answer...

You can still use automatic properties in C# 3 when targeting .NET 2.0, along with quite a few other C# 3 features. Unlike (say) expression trees, automatic properties don't need anything special from the CLR or the framework, beyond the [CompilerGenerated] attribute (which was introduced in .NET 2.0).

So if you're using VS2008 or VS2010, then it would be worth using an automatic property.

For what it's worth though, I'd like this ability too. I'd like to be able to scope variables within a property:

 public string Name
 {
     private string name;
     get { return name; }
     set { name = value; }
 }

I view this a bit like making a private variable readonly - it makes no difference to clients, but it helps to enforce correctness within the class code itself.

Solution 2:

You can accomplish this via inheritance:

abstract class A // A is not instantiatable due to being abstract
{
    private string m_hello = null;

    public string Hello
    {
         get{return m_hello;}
         set{m_hello = value;}
    }
}

class B : A
{
    // B now cannot access the private variable, use B in your code instead of A
}

I am not claiming that this is good. Just that it can be done.

Solution 3:

No there is not a way to do that, other than to simply follow your own convention and do this.Hello if you really need to go through your public property.

I don't see why you would need/want to do this either, as since it is your internal class, you are the one in control of the code and you can define what/how it is used, so there shouldn't be an issue.

Solution 4:

No. Any method inside the class will have access to both.

Your team should standardize on which to use (Property or private variable).

Once you decide which to use, you could try to use a custom FxCop rule to enforce the standard.