Laurent Bugnion [MVP] napisał(a):
Hi,
Doug wrote:
>Hi
I have been told about the following code:
private string boxLabel;
public string BoxLabel
{
get { return boxLabel;}
set {boxLabel = value;}
}
does this routine set the value of the private string to be the same
as the value input by the public string or is it the other way? Could
you please tell me in simple words what this is used for?
Thanks
doug
Properties are a way to control access to your private members. The
example here above is very trivial, as it simply (set) copies the given
value to the private member and (get) returns the private member without
modifying it.
Often, the set part is used to check the given value in order to avoid
later errors, or to simplify code. For example, you can do something like:
private string myString = "";
public string MyString
{
set
{
if ( value == null )
{
value = "";
}
myString = value;
}
}
This code ensures that the private member "myString" can never be set to
null. This way, the code using myString doesn't need to check everytime
to avoid null reference exception.
There are many other ways to use properties, but generally, you can say
that they are used to control user's access to private members.
It is good practice to never return attributes, but always properties.
The reason is that it allows later changes to your code without
modifying the interface to your class. The code you posted, though
trivial, follows that rule.
HTH,
Laurent
You can use Properties too if you need one way direction "communication
with variables". For example
private string s;
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
public string Name
{
get {return s;}
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
code above allows you to only read value of s, not to write(!).
Another idea is to combine return result depending on many than one
variable.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
private bool var1, var2, var3;
.... // some code to modify values (i.e. test with aswer true or false)
public string TestResult
{
get
{
if((var1 && var2) || (var1 && var3) || (var2 && var3))
return "Test passed successfully";
else
return "You need to try again, good luck!";
}
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Generally what for you use properties ... it is up to you. It could only
return or set value from variable, raise event (before or after settings
a variable), get/set values to group of variables (like methods), test
something and many more.
best,
Sławomir