Browse By

Extension Methods in C#

C# 3.0 came with a productive feature called Extension Methods. This created many questions in the Developer’s mind like what is the exact use and how it can be implemented in development. Let us dig into some of its usage and how it helps C# developers.

What is Extension Methods?

Extension Methods enable us to add methods to existing types without creating a new derived type, recompiling or otherwise modifying the original type.

The Extension Methods are a special kind of static method but they are called as if they were instance method of already existing type.

Why do we need Extension Methods?

We can create and add new methods to objects that were already defined. More specifically it helps in a situation when we don’t have ownership to particular source of the original object.

Here comes the question from other language users that “Why can’t we just add a new method to the own class itself?”. The answer is simply just to increase the Code productivity.

intellisense_csharp_dartleThe Extension Methods will make code writing so easy. It will be hooked up in the intellisense if added to any basic types.

 

Simple Example

            For instance consider we would like to add a text “Dartle” as a prefix in various occurrence to the strings in our class. Rather creating a method that concatenates the text, we are going to extend in the basic type as follows.

//Extension Class
public static class DartleExtension
{
//Extension Method
public static string PrefixDartle(this string value)
{
return "Dartle " + value;
}
}

class Program
{
static void Main(string[] args)
{
string value1 = "Value number one";
string value2 = "Value number two";
//Accessing Extension Method in our Class
string value3 = value1.PrefixDartle();
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(value3);
Console.ReadKey();
}
}

Here we have created a new static class(DartleExtension) which holds our Extension Method(prefixDartle). Please note that we are passing on “this” keyword as a parameter.

So it make us easier to use just like implementing instance method.

Role of Extension Methods in LINQ

            LINQ is made all about Extension Methods. It works upon most of the IEnumerable types.

For Instance;

int[] arr = { 2, 3, 4, 5, 5 };
Console.WriteLine(arr.Sum());

The output value should be 19.

Points to Remember

  • Increases Productivity in Code writing
  • Extension methods cannot be used to override existing methods
  • Extension methods should be a Top End Static class
  • Extension method cannot be used or applied to events, properties and fields
  • Extension methods plays a vital role in LINQ technology

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>