Posted by: Cirilo Meggiolaro | 12/24/2008

Tip of the day #71 – Extension methods

Have you heard about extension methods? This is a feature from C# 3.0 that I haven’t seen so much on the codes I’ve worked on but it is really cool.

The idea of an extension method is to create methods that may “extend” the functionality of an object does not matter if it is a reference type, primitive type or any custom object that you come to code.

Ok, if you want to extend the functionality of a custom class you may create a new method or a derived class, right? It is not a rule. If the class has been defined as sealed you cannot inherit or if you don’t have access to the source code how do you create a new method?

Rules

The rules to create an extension method are:

  • The method must be static;
  • The method must be created under a top-level static class;
  • The method must have at least one parameter declared with the keyword this before the data type definition. The data type for this parameter dictates the object that has been extended. i.E.: If you want to extend a string, the parameter will be something like this: this string myString.

How to…

We are going to check three examples:

  • How to extend a string;
  • How to extend a primitive type like a decimal;
  • How to extend a custom object.

Extending a string

The following code demonstrates how to create an extension method that converts a string to its reverse order. The method is static and is located under a static class as well. Note that the parameter is defined with the keyword “this”.

public static class StringExtensions
{
    public static string RevertString(this string originalText)
    {
        char[] arrTxt = originalText.ToCharArray();
        Array.Reverse(arrTxt);
        return new string(arrTxt);
    }
}

From any method in your application you may consume the extended method like this:

string txt = “This is a simple text”;
Console.WriteLine(txt.RevertString());

/// Output: txet elpmis a si sihT

Extending a primitive type

There is no secret to extend a primitive type. The rules are the same than we’ve seen so far.

public static class DecimalExtensions
{
    public static decimal SquareFeet(this decimal n1)
    {
         return (n1 * n1);
    }
}

decimal number = 12;
Console.WriteLine(number.SquareFeet());

/// Output: 144

Extending a custom object

Again the same rules apply. Let’s assume we have a class that identifies a Customer. Outside this class we are going to create a method to retrieve the full customer name (for example purposes only):

public class Customer
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Customer(int id, string firstName, string lastName)
    {
        this.ID = id;
        this.FirstName = firstName;
        this.LastName = lastName;
    }
}

public static class CustomerExtensions
{
    public static string GetFullName(this Customer c)
    {
        return string.Format(“{0} {1}”, c.FirstName, c.LastName);
    }
}

Customer c = new Customer(1, “Bill”, “Smith”);
Console.WriteLine(c.GetFullName());

/// Output: Bill Smith

Parameterized extension methods

Create an extension method with parameters is pretty straightforward. Keep in mind that when you invoke the method, except for the first parameter defined with the “this” keyword, you need to pass all other parameters. The following code snippet demonstrates the use of parameters in a function that retrieves the integer part of a division:

public static class DecimalExtensions
{
    public static int Mod(this decimal n1, decimal n2)
    {
        return Convert.ToInt32(n1 % n2);
    }
}

decimal number = 12;
Console.WriteLine(number.Mod(5));

/// Output: 2

Advertisements

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

Categories

%d bloggers like this: