Using Property Accessors With Private Variables

When learning about Object Oriented programming in .net and specifically C#, we are taught to always use public properties with accessors to expose a particular variable:

private string _myVar;

public string MyVar
{
   
get { return _myVar; }
   
set { _myVar = value; }
}

Which is normally the beginning and the end of the conversation. However, you can also use accessors (getters/setters) to encapsulate complex or receptive logic for private variables as well. This is especially useful in ASP.NET programming where you often have to deal with state management. For example to retrieve a value from the QueryString you would write something like:

int myVar;

if ( Request.QueryString["MyVar"] != null )
{
     myVar = Convert.ToInt32( Request.QueryString["MyVar"].ToString() );
}

Which is fine, unless you need to use that variable in more than one place. You could use a function to check the querystring and retrieve that value, but accessors offer a better way to encapsulate that code for reuse. Consider the following examples:

//Read-Only string from the QueryString
private string myQueryStringVar
{
   
get 
    {
       
if ( Request.QueryString["MyVar"] != null )
        {
           
return Request.QueryString["MyVar"].ToString();
        }

       
return string.Empty;
    }
}

//Read-Write string from the ViewState
private string myViewStateVar
{
   
get 
    {
       
if ( ViewState["MyVar"] != null )
        {
           
return Request.QueryString["MyVar"].ToString();
        }

       
return string.Empty;
    }
   
set { ViewState["MyVar"] = value; }
}

//
Encapsulating a dropdownlist
private int myDropDownList
{
   
get
    {
       
return Convert.ToInt32( someList.SelectedValue );
    }
   
set
    {
        ListItem li 
= someList.Items.FindByValue(value.ToString());
       
       
if (li != null)
        {
            li.Selected
= true;
        }
    }
}

Which you can use exactly as privately declared variables:

someLabel.Text = myQueryStringVar;
myViewStateVar
= "Hello World";
someTextBox.Text
= myViewStateVar;

You can hide a good deal of functionality through accessors or mix and match techniques. Here's an example I recently used in a project which checks for a QueryString value on a fresh page load to initialize a variable, then uses the ViewState to persist that variable during the rest of the page's lifespan:

private int myVar
{
   
get
    {
       
if ( !IsPostBack && Request.QueryString["MyVar"] != null )
        {
           
return int.Parse(Request.QueryString["MyVar"]);//you might want to use some validation
        }
       
       
if (ViewState["MyVar"] != null)
        {
           
return (int)ViewState["MyVar"];
        }

       
return -1;//or your favorite null value
    }
   
set
    {
        ViewState[
"MyVar"] = value;
    }

}

As you can see, it's pretty easy to write accessors for your stateful or logic driven  variables and reduce and really simplify your code.

Print | posted on Sunday, May 09, 2004 4:41 PM

Comments on this post

# re: Using Property Accessors With Private Variables

Requesting Gravatar...
What do you think about encapsulating all of that into its own manager class:

public class Int32VarManager
{
public Int32VarManager(Control owner, string varName)
{
}

public int ViewState
{
// ...
}

public int QueryString
{
// ...
}

//...

}

Then, you could have something like this in your control code:

private Int32VarManager _myVar;
public Int32VarManager MyVar
{
get
{
if (_myVar == null)
{
_myVar = new Int32VarManaber(this, "myVar");
}
return _myVar;
}
}
Left by Dimitri Glazkov on May 21, 2004 7:39 AM

Your comment:

 (will show your gravatar)
 
Please add 8 and 6 and type the answer here: