Date Handling Tip Part 2: Get the Month Name as Extension Method

After my last post on the GetMonthName, I had a question on how to add this method to the DateTime class as an Extension method. I thought this would make a good follow-up, so here is how you can accomplish this.

First, let's do the C# extension method. Add a new class to your project. For this example, I called the class "MyExtensions". This class needs to be defined as a static class. Next add a public method called GetMonthName. This is a static method and accepts a DateTime object as a parameter. Remember that with Extension methods you need to use the keyword "this" in front of the parameter. Below is the C# example:

public static class MyExtensions
{
  public static string GetMonthName(this DateTime dateValue)
  {
    DateTimeFormatInfo info = new DateTimeFormatInfo();

    return info.MonthNames[dateValue.Month - 1];
  }
}


To use this extension method you can write code like the following:

DateTime value;

value = DateTime.Now;

MessageBox.Show(value.GetMonthName());

Now, let's take a look at how to accomplish the same thing in Visual Basic. With Visual Basic there is no such thing as a Shared class, so instead you use a Module. So, we add a module to our project called "MyExtensions" to our project. You have to import the System.Runtime.CompilerServices namespace as we will be attaching an Attribute to our extension method. Below is what our new module now looks like.

Imports System.Runtime.CompilerServices
Imports System.Globalization

Module MyExtensions
  <Extension()> _
  Public Function GetMonthName(ByVal dateValue As Date) As String
    Dim info As New DateTimeFormatInfo

    Return info.MonthNames(dateValue.Month - 1)
  End Function
End Module

Now, to use this new extension method simply write code like the following:

Dim value As Date

value = Now

MessageBox.Show(value.GetMonthName())

Good Luck With Your Coding,
Paul Sheriff

** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".

Past Blog Content

Blog Archive

5 Comments

Comments have been disabled for this content.