Extension Methods

Extension methods allow you to add functionality to existing classes, whether they are .NET Framework classes or your own.  The MSDN library offers more information on extension methods in C# 3.0 and Visual Basic 2008.

I often use extension methods for formatting Double values.  For some reason, I can’t seem to remember how these are supposed to be formatted, so I created extension methods for this purpose.  The following class shows the code that is needed to format a Double value using the local regional settings, or using a specific culture:

using System;
using System.Globalization;

namespace IDevelop.Framework.Utilities.Extensions
{
  public static class DoubleExtensions
  {
    public static string ToLocalCurrencyString(this double value)
    {
      return (String.Format("{0:C}", value));
    }

    public static string ToSpecificCurrencyString(this double value,
      string cultureName)
    {
      CultureInfo culture = new CultureInfo(cultureName);
      return (string.Format(culture, "{0:C}", value));
    }
  }
}

In order to use these extension methods, make sure that the class in which you use them has a using statement to import the namespace in which the extension methods are located. Then, you can call the two extension methods as shown in the following two samples:

double localCurrencyString = 9.95;
double specificCurrencyString = 11.21;

Debug.WriteLine("Local: " +
     localCurrencyString.ToLocalCurrencyString());
Debug.WriteLine("Specific: " +
     specificCurrencyString.ToSpecificCurrencyString("nl-NL"));

This outputs the following strings:

Local: $9.95
Specific: € 11,21

These are just two simple examples that show how extension methods can be used to add functionality to existing classes.

If you found this post helpful, please click below to “Kick” it:

kick it on DotNetKicks.com

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: