Information Technology Reference
In-Depth Information
The .NET Framework assumes that you'll use properties for your public data
members. In fact, the data binding classes in the .NET Framework sup-
port properties, not public data members. This is true for all the data bind-
ing libraries: WPF, Windows Forms, Web Forms, and Silverlight. Data
binding ties a property of an object to a user interface control. The data
binding mechanism uses reflection to find a named property in a type:
textBoxCity.DataBindings.Add(
"Text"
,
address,
"City"
);
The previous code binds the Text property of the textBoxCity control to
the City property of the address object. It will not work with a public data
member named City; the Framework Class Library designers did not sup-
port that practice. Public data members are bad practice, so support for
them was not added. Their decision simply gives you yet another reason
to follow the proper object-oriented techniques.
Ye s , d a t a b i n d i n g a p p l i e s o n l y t o t h o s e c l a s s e s t h a t c o n t a i n e l e m e n t s t h a t
are displayed in your user interface logic. But that doesn't mean proper-
ties should be used exclusively in UI logic. You should use properties for
other classes and structures. Properties are far easier to change as you dis-
cover new requirements or behaviors over time. You might soon decide
that your customer type should never have a blank name. If you used a
public property for Name, that's easy to fix in one location:
public class
Customer
{
private string
name;
public string
Name
{
get
{
return
name; }
set
{
if
(
string
.IsNullOrEmpty(
value
))
throw new
ArgumentException
(
"Name cannot be blank"
,
"Name"
);
name =
value
;
}
// More Elided.
}
}