Refactoring Idea

As I was refactoring some of my code at work today, I found another example of refactoring that would come in handy: De-sugaring code segments that are syntactically sugared.

In my case, I had to support a changed business rule that required nullable DateTime objects instead of ValueType DateTime objects. So I tried to change

DateTime dtNull = ( /* my condition */ ) ? new DateTime() : DateTime.Today;

to

DateTime? dtNull = ( /* my condition */ ) ? null : DateTime.Today;

Of course, Visual Studio gives me a compiler error if I make this change because “there is no implicit converstion between <null> and ‘System.DateTime'”. However, the following does work:

DateTime? dtNull;
if ( /* my condition */ ) {
    dtNull = null; }
else {
    dtNull = DateTime.Today; }

It seems that refactoring something like this should be very easy to automate. Unfortunately, to my knowledge, Visual Studio 2005 is not as extensible in the area of refactoring as it is in the area of Code Snippets.

Leave a Reply

Your email address will not be published. Required fields are marked *