Posts Tagged ‘C#’

When creating an application that requires a person’s age, we typically store the date of birth and calculate their age in years from that.  I usually store my user’s date of birth in a property of type DateTime.  To make it easy to calculate the user’s age based on this property, I decided to take advantage of .NET’s new extension methods feature.  By adding an extension method to .NET’s native DateTime type, we can quickly calculate the age of any object that has a DateTime property. 

We will create two extension methods.  One will accept no parameters and return the age based on the current date.  The overload of this method will accept an future date to base the age calculation on.  This would be useful if you wanted to know what the person’s age will be on some future date.  As we see below, they are very straightforward.

Once we have that, we just need to import the namespace that our extension methods are in.  All your DateTime types will now have this method available via intellisense.

To see the effect of our new extension method, let’s see what Jim Morrison’s current age would be followed by how old he’ll be in a number of days.  Finally, let’s see how long ago the US declared independence from the British.

The previous code will produce the following output: 


If you want to find out more about authoring your own extension methods, check out this article

Hope this helps.