10.3. What to Do if an Error Occurs in a Property Method

There will be times when a bogus value reaches a property method. However, the set statement block is used to change the state of the object and not to return a value to the caller. So how do you communicate to the user that your class code read a bad data value in a property method?

Your first approach might to be to use a MessageBox object to display a message to the user that a bad value for a property was read. The problem with this approach is that the data manipulation is going on in the class, not in frmMain where the end user is interacting. When you are writing code for a class, you should always keep in mind that your user is a programmer, not the end user running the program. Because of this, you need to let the person using your class know that something's amiss. (A general style convention is that property methods do not use MessageBox objects.)

The main purpose of a set statement block is to change the value of the property associated with the method. Because a change in the value of a class property also means a change in the state of the object, the safest thing to do when an error is detected is to leave the state of the object unchanged. For example, if a bogus value for a month reaches the set statement block in Listing 10-3, the new value for month is ignored and the state of the object remains unchanged. It would be the responsibility of the programmer using your class to detect that the set operation ...

Get Beginning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.