Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

oop

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.

like image 682
adamwtiko Avatar asked Jul 16 '10 14:07

adamwtiko


People also ask

Can private variables be accessed in public methods?

But after the object is created you can only access the private variable through the public methods of the constructor and no longer change it directly in any way.

Why use private variables instead of public?

Class variables that are declared as private can not be referred to from other classes, they are only visible within their own class. It is considered better programming practice to use private rather than public class variables, and you should aim to do this in the remainder of the course.

Can private variables be accessed by objects?

We cannot access a private variable of a class from an object, which is created outside the class, but it is possible to access when the same object is created inside the class, itself.

Why should member variables be private?

By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.


1 Answers

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.

like image 98
Jon Skeet Avatar answered Nov 15 '22 16:11

Jon Skeet