Preserving the cursor when putting up an hour glass - Win32 best practice in a .NET world
Today's quickie tip comes from the world of Win32 best practice.
In Win32, we were taught to return resources to the state they were before we were using them. This is good OO programming practice generally (makes your operations more encapsulated). My specific example here is the best way to put up an hourglass cursor to the user for a lengthy op.
void Save()
{
// save the old cursor...
Cursor oldCursor = this.Cursor;
// put up an hourglass...
this.Cursor = Cursors.WaitCursor;
try
{
// do some work...
}
finally
{
// restore the old cursor....
this.Cursor = oldCursor;
}
}
The idea behind this apporach is that you remove the assumption that the cursor was a default cursor before you got into this method. The bad way of doing this is to explictly set the cursor back to what you think it was before you got into the method. This may not be the case as another method may have changed the cursor before you get your chance to run. In effect, you would have messed up the state of the object and broken the operation of the up-level method.
Moral: always return state back to how it was before you changed it, rather than what you think it was.