c sharp extension methods

C sharp extension methods

programming with C# sharp extension methods allow us to write cleaner, simpler and more readable code.
But before we see how they are used, lets see some example code without using Extension methods. Below we will show you step by step as we will introduce the Extension methods. This is actually very easy to learn, almost like a regular method.

Lets assume we need a method that will revert the value of a String variable. A method would probably look something like this:


public static class MyCommonMethods
{
public static string MyReverse(string word)
{
string result = "";
for (int i = word.Length-1; i >= 0; i--)
{
result += word[i];
}
return result;
}
}

We can use this method in our application (console for our demonstration) like below:


class Program
{
static void Main(string[] args)
{
string myName = "Aleksandar";
myName = MyCommonMethods.MyReverse(myName);
Console.WriteLine(myName);
}
}

So far so good, but now lets see what we will change with the use of Extension methods.
When speaking about Extension methods, we have to have our mind the following:
Extension methods allow us to add methods in already existing types, without changing the code of that type, nor recompiling it. Further more, we don’t even need to have access to the source code of that type at all.
How is that possible? With c# it is very easy and simple. Speaking about c# this is my favorite phrase: When it comes to programming, C++ is legislation for it, but C#, is the constitution :). Below you can find out why.


public static class MyExtensionMethods
{
public static string MyReverse(this string word)
{
string result = "";
for (int i = word.Length - 1; i >= 0; i--)
{
result += word[i];
}
return result;
}
}

And that is it. Only few things to know when writing an Extension method are:

  • That method has to be static, and has to live inside static class.
  • The first parameter has to have this modifier in front
  • The type of the first parameter that has this modifier is the type that is being extended

Knowing all this, we can use the method above like this:


class Program
{
static void Main(string[] args)
{
string myName = "Aleksandar";
myName = myName.MyReverse();
Console.WriteLine(myName);
}
}

Also the method is in the intellisense of the extended type like in the picture below in Visual Studio.
C Sharp extension methods
I hope you will find my tutorial useful how to use extension methods in C# (C Sharp)

Posted in C#, Programming, Tutorials, Visual Studio and tagged , , , , , , , .

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.