In this article, we will learn:

  • Extending existing types in C#
  • Extension Methods in C#
  • Use cases for Extension Methods in C#

Extending existing types in C#

C# supports several ways to extend existing types without modifying the existing code.
There are two different ways : extension methods and overriding.

Extension methods:

Extension methods enables you to add new capabilities to an existing type. You don’t need to make any modifications to the existing type, just bring the extension method into scope and you can call it like a regular instance method.
Extension methods need to be declared in a nongeneric, non-nested, static class.

Example:

   namespace ConsoleApplication11
{
   //extension methods must be defined in a static class
    static class IntMethods
    {
        //extension methods must be static
        //the this keyword tells C# that this is an extension method
        public static bool IsPrime(this int number)
        {
            //check for evenness
            if (number % 2 == 0)
            {
                if (number == 2)
                    return true;
                return false;
            }
            //you don’t need to check past the square root
            int max = (int)Math.Sqrt(number);
            for (int i = 3; i <= max; i += 2)
            {
                if ((number % i) == 0)
                {
                    return false;
                }
            }
            return true;
        }
    }
class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 100; ++i)
        {
            if (i.IsPrime())
            {
                Console.WriteLine(i);
            }
        }
        Console.ReadKey();
    }
}
}

Note:

  • The difference between a regular static method and an extension method is the special this keyword for the first argument.
  • Extension method cannot be declared on a class or struct.
  • It can also be declared on an interface (such as IEnumerable<T>). Normally, an interface wouldn’t have any implementation. With extension methods, however, you can add methods that will be available on every concrete implementation of the interface
  • Language Integrated Query (LINQ) is one of the best examples of how you can use this technique to enhance existing code.

Use cases for Extension Methods in C#

Let’s discuss few use cases to use Extension methods.

1. Attach Metadata to Enums with Extension Methods

you can add a method to your enumeration to access the values you attached in attributes.

Let’s create an attribute for this example.

[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class CultureAttribute : Attribute
{
    string _culture;
    public string Culture
    {
        get
        {
            return _culture;
        }
    }
    public CultureAttribute(string culture)
    {
        _culture = culture;
    }
}

Let’s create an Enum :

enum BookLanguage
{
    None = 0,
    [Culture(“en-US”)]
    [Culture(“en-UK”)]
    English = 1,
    [Culture(“es-MX”)]
    [Culture(“es-ES”)]
    Spanish = 2,
    [Culture(“it-IT”)]
    Italian = 3,
    [Culture(“fr-FR”)]
    [Culture(“fr-BE”)]
    French = 4,
};

Finally, we need to add the extension method to access these attributes:

static class CultureExtensions
{
    public static string[] GetCultures(this BookLanguage language)
{
//note: this will only work for single-value genres
CultureAttribute[] attributes =
(CultureAttribute[])language.GetType().GetField(
language.ToString()).GetCustomAttributes(typeof(CultureAttribute),
string[] cultures = new string[attributes.Length];
for (int i = 0; i < attributes.Length; i++)
{
cultures[i] = attributes[i].Culture;
}
return cultures;
}
}

Now let’s test this example:

PrintCultures(BookLanguage.English);
PrintCultures(BookLanguage.Spanish);
static void PrintCultures(BookLanguage language)
{
Console.WriteLine(“Cultures for {0}:”, language);
foreach (string culture in language.GetCultures())
{
Console.WriteLine(“\t” + culture);
}
}

The output will be:

Cultures for English:
en-UK
en-US
Cultures for Spanish:
es-MX
es-ES

2. Speed Up Queries with PLINQ

You can use the AsParallel() extension method to speed up queries with PLINQ

If your original query is

var query = from val in data
where (ComplexCriteria(val)==true)
select val;
foreach (var q in query)
{
//process result
} 

where ComplexCriteria() is just an arbitrary Boolean function that examines the values in the data, then you can parallelize this with a simple addition:
var query = from val in data.AsParallel()
where (ComplexCriteria(val)==true)
select val;
foreach (var q in query)
{
//process result
}

A lot of extension methods are supported by Visual studio. Visual Studio marks extension methods in IntelliSense with a down arrow to make them easy to identify.

Summary:

In this article, we have learned the Extension method in C# and different use cases for it.

Thanks for visiting !!

© 2016, Csharp Star. All rights reserved.

1 Comment

  1. Junior Pacheco

    Nice article and explications. This tips are very goods!

    Reply

Leave a Reply