Wednesday, December 5, 2007

Why We Use Properties in .NET

Properties are extremely useful in .NET for debugging, validation, raising an event when data is changed and changing data in other fields.

Let's look at an example.


public class Email
{
private string emailAddress;

public string EmailAddress
{
get
{
return emailAddress;
}
set
{
if (isValidEmail(value))
{
emailAddress = value;
}
}
}

public bool isValidEmail(string inputEmail)
{
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
{
return (false);
//and possibly log error
}
}
}

In this example we have a private field named emailAddress and a Property named EmailAddress. This is useful we want to validate the email address before setting it. We simply test the value using isValidEmail() in the property setter. This allows us to omit this code from our procedural code(where we don't want to see it anyway) .

The Downside is that it does create some overhead and it is more typing. Hardly a sacrifice in todays world.

Properties are quite simply a more robust and future proof way to handle data. It is not necessary to use properties by any means but if there is any question as to the validity of data being passed in or if it is likely that the library will evolve then it is a good idea to use properties.

No comments: