Modify/Access private field from within the class through property or variable?

M

Mark

Generally it is recommended to have private variables and allow them
to be accessed through public properties. However, in the class
itself, when i want to modify or read that variable, should i go
through the property or just directly access the variable? What is the
microsoft way?

private _firtName;

public string FirstName;
{
get{return _firstName;}
set{_firstName = value;}
}

public void DoSomething()
{
_firstName = _firstName +"__asdfasd__" + _firstName;
}
// OR
public void DoSomething()
{
FirstName= FirstName+ "__asdfasd__" + FirstName;
}

What is the recommended way?

Thanks

Mark
 
A

Andreas Håkansson

Mark,

One of the main reasons for using properties to access private member
variables is that you can provide programming logic in the get/set code
sections. Another (good) reason for going through the properties, even
from inside the class, is that the code do not need to know how the
information, returned by the property, was fecthed. Perhaps you have
a property called GetEmployeeID() which in Version 1 of your class
reads a private member

private int emplyeeId;

Now in Version 2 you alter the class to fetch the information from a
database. Now the calling code (the code using the property, which
also includes code in the same class) does not need to know the
difference on HOW to get the information, just take part of it.

So what it comes down to, is that you hide any logic you might need
to perform to get the return value. If you did not call through the
property from withing the class, you would have to change the logic
at every single place who needs this member.

My suggestion is to always call privat member through public properties
if they are avalible.

Just my 2 cents..

HTH,

//Andreas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top