Extension Methods in C#

rasheedmozaffar

Rasheed K Mozaffar

Posted on February 4, 2023

Extension Methods in C#

Hey There !

We have a cool topic to address today , it goes by the name of Extension Methods , so , what are they , how to use them , and why would you even use them ?

We'll kick it off with an overview from Microsoft Docs

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there's no apparent difference between calling an extension method and the methods defined in a type.

This is a brief overview of what extension methods are , by their name , they are extensions for the types that they're applied on , which means we are extending on the functionality of a certain type , this type could be a pre-defined type or a user-defined type.

Initially , this overview is cool and all , but how do we create and add extension methods to types ? This's what we'll be working on next !

Creating a project

For now , we'll be keeping it simple , so for that , we're gonna use a console application , so fire up your Text Editor and create a new .Net Core Console Application , you can use any code editor you like as long you can write C# in it.

Setting up the scene

To write our first extension method , we'll be defining a very simple type and we'll call it Person.

So inside your project , create a new class and name it Person.cs , inside your newly created class , add these 2 properties

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Ok , I suppose this is straight simple and easy for now , we just declared a new type with 2 string properties that represent the first and last name of a person , now , we'll create an extension method that will return the full name of the person that it's applied on , to do that , we need to create a new folder and name it Extensions , it's not mandatory though , but to remain precise and organized , we'll try to segregate things up a bit.

In the root of your project , create a new folder and add a class to it named MyExtensions.cs.

Now if you take a look back at that overview up top , it mentioned that extension methods are static methods , to add to it , they must exist in a static class , so for that , we gotta mark MyExtensions class as a static class , and its members should also be static since static classes only accept static members.

Your class should look something like this:


public static class MyExtensions
{
    //Extension Methods Go Here.
}

Enter fullscreen mode Exit fullscreen mode

Now we're all set to start extending our Person type , which is what we'll be doing next.

Creating the GetFullName extension method

Our Person type has a first and last name properties , but what if in a certain case , we wanted to get the full name of our person , for that reason , we'll be extending on that type.

Remember , extension methods are static methods , don't forget to add the static keyword to the methods.

Add this code block to create an extension method that returns the full name of a person , the code is as follows:


public static string GetFullName(this Person person)
{
    return $"{person.FirstName} {person.LastName}";
}

Enter fullscreen mode Exit fullscreen mode

This code looks very similar if not identical to declaring a normal method , it's literally the same as an instance method , the only difference here is inside the parameters' parentheses , you can see the this keyword , what does it mean here ?
In this context , it indicates what type this method is operating on , in this case , it's operating on the Person type , to extend/add on it , the GetFullName method which basically takes the FirstName and LastName , put them together , and separate them with a space , and return it back.

To get the full name , we used string interpolation which is a handy feature to build strings with such ease , if you don't know how to use string interpolation , you can start doing so by preceding the double quotes with a dollar sign like this $"" , now inside the string , you can plug in values , expressions that return values , or even invoke methods that return something , which will do the work , and then it'll evaluate the expression and plug the returned value in that place , all by using curly braces within the double quotes {Expression}.

So by now , we created a new type , we added an extension method for it , but how do we invoke it ? Well , invoking an extension method is the same as invoking any normal method , you do so by using the dot operator.

To see that in action , I'll go to Program.cs which is where our code will go , and create a new instance of the Person class and name it somePerson , like this:


Person somePerson = new()
{
    FirstName = "Tony",
    LastName = "Stark"
};

Enter fullscreen mode Exit fullscreen mode

I've done both the declaration and initialization in one go , we could've used a different syntax , but that's better and more efficient, now we are ready to to make a call for our extension method.

Import the namespace

If you created the MyExtensions.cs in a separate folder , then you need to import the namespace so we can access them inside of Program.cs , so make sure to stick the using directive up top.

Get the Full Name

if you recall , our extension method returns a string , so we should declare a string variable to hold the full name , we can do that as follows:

string fullName = somePerson.GetFullName();

See , this is how simple it is to call an extension method , this method takes no parameters , it just applies on the type calling , in this scenario , it's somePerson here which is of type Person.

If you wanna see the result , you can do a Console.WriteLine(fullName); and you'll see the console outputting Tony Stark.

Amazing , you created your first extension method !

Let's write another one that makes the person able to say a message , this one will take another parameter , other than the type it's being applied on .

Add this piece of code to the extensions static class:


public static string PersonSayMessage(this Person person, string message)
{
    return $"{person.FirstName} says {message}";
}

Enter fullscreen mode Exit fullscreen mode

Ok , this again is pretty simple , go back to Program.cs and a create a variable of type string , add a piece of string that you want your person to say , and then do a Console.WrirteLine();.
This is how it should be like:


string message = "Iron Man is the best Avenger !";

Console.WriteLine(person.PersonSayMessage(message));

//OUTPUT: Tony says Iron Man is the best Avenger !

Enter fullscreen mode Exit fullscreen mode

Hooray 🎊

You've learned the basics of extension methods , and you created a couple of them , in case you want to practice a bit more beyond the fundamentals , you can do this exercise.

  1. Create an extension method that returns how many letters are there in the person's full name.

If you wanna dive even deeper , I suggest you check out the documentation on Microsoft Learn for a more detailed explanation.
You can do that through the following link

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

I'm planning on writing an article on how to use extension methods to more better clean up your code if you're working on an Asp .Net Core application , but that's more advanced , and for a later day , for now , try to grasp the basics and understand how to use extension methods further more , also make sure to write some of your own , you can also see extension methods in action if you refer back to my LINQ article , I've used many of the extension methods that come with LINQ straight out of the box.

Goodbye Now

💖 💪 🙅 🚩
rasheedmozaffar
Rasheed K Mozaffar

Posted on February 4, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Extension Methods in C#
dotnet Extension Methods in C#

February 4, 2023