extension methods


Extension methods were introduced with .NET 3.5.  They allow you to add functionality (methods) to .NET types or object types. 

Here is a simple template of an extension method:

public static class MyExtensionsClass

{
    public static returntype MyExtensionMethod(this thetypetoextend variabletoholdthevalueinthetype, otherparameters)
    {
        Do something….
        return returntype;
    }
}

Here is an example of an extension method to the .NET decimal type.  The name of the method is “TaxIt”.  It basically accepts a state parameter and if the state = “AZ” it adds the Arizona tax to the value and returns the result.

The keyword “this” in the first parameter basically says that the extended method will be made available in all decimal types.

namespace NTierWeb.Pages
{

public static class MyExtendedMethods
{       
    //method adds tax to a value
    public static decimal TaxIt(this decimal d, string state)
    {
       if (state == "AZ")
        {
            return (d * 1.056M);
        }
        else
        {
            return d;
        }
    }
}

}

To use your extended method simply import the namespace of the extended method into your class with a “using” statement.

Notice that the “TaxIt” method is now available via intellisense to any decimal.  I’m setting the preTaxTotal decimal to 20 and when I call TaxIt on it it will pass that value (20) into the method and will be captured by the “(this decimal d” parameter.  However, note that I did not pass the value 20 into the method.  All I passed was the other parameter”AZ” for the state.

using NTierWeb.Pages;

public class DemoExtensions
{
    public void testExtension()
    {
            decimal preTaxTotal = 20;
            decimal afterTaxTotal = preTaxTotal.TaxIt("AZ");
    }

}

Here is the sequence step by step:

About to call the TaxIt method:

image

Entering the TaxIt method.  Notice the value “20” being passed:

image

Since the state parameter = “AZ” it will multiply the value by the Arizona Tax:

image

Upon returning from the TaxIt method:

image

No comments:

Post a Comment