Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in H:\root\home\sklibraries-001\www\rajmhr\wp-content\plugins\wp-markdown\markdownify\markdownify.php on line 299
How to best use Extension Methods – RajTech

How to best use Extension Methods

C# is reach in programming style. Extension methods, introduced from c# 3.0, is one of them. Extension methods are just a static methods which are accessed in different way. The sole purpose of extension methods is to make readable code and extend the functionality of existing type.

Criteria for extension methods:

  • Static class with static function name.
  • Uses “this” keyword as first parameter.

Precaution:

  • Extension method with same class name will never be called.

Disadvantages:

  • Difficult to track error.

Practical uses:

  • Heavily used in Fluent Interface.
  • Linq Query

The following snippets shows the implementation of Extension methods. Here, “Extension”  a class name is static and also “TotalEventCount()” method is. “this” keyword is used for parameter as shown below.

public static class <strong>Extension</strong>
  {
      static readonly List<int> EvenCollection = new List<int>();
      public static IEnumerable<int> TotalEvenCount(<strong>this</strong> IEnumerable<int> input)
      {
          foreach (var item in input)
          {
              if (IsEven(item))
              {
                  EvenCollection.Add(item);
              }
          }
          return EvenCollection;
      }
      private static bool IsEven(int item)
      {
          return item % 2 == 0;
      }

This is the main program. That uses the extension method.

class Program
{
    static void Main(string[] args)
    {
        var numberCollections = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        var result = numberCollections.TotalEvenCount();
        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
        Console.ReadLine();
    }
}

Here, collection “numberCollection ” is been treated as a parameter and TotalEventCount() is the function defined in Extension method at line no. 6.

Summary

Extension methods affect syntax, not execution. Remember, you can add extension methods to any type, even a value type.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *