Extension Methods in C#

Today I would like to talk about Extension methods. They allow you to add methods to existing types without having to create a derived class or modifying the original one, but they are called like if they were instance methods.

For example, let’s say you are creating multiple rows into a table in different parts of your code, looking something like this:

var table = new Table();
var row = new Row();
var cell = new Cell { Text = "test1" };
row.Cells.Add(cell);
cell = new Cell { Text = "test2" };
row.Cells.Add(cell);
table.Rows.Add(row);

Wouldn’t be nice to have a simpler method into the Table class, allowing us to do this in a nicer way? However, Table is coming with the .NET framework so how can we add our own method into an existing type? Extension methods would help us with this.

public static class MyExtensionMethods
{
   public static void CreateAndAddCell(this TableRow row, string text)
   {
      row.Cells.Add(new TableCell { Text = text });
   }
} 

Notice the “this” on the first parameter. This is indicating that any object TableRow type will now have the CreateAndAddCell (remember to include “using MyExtensionMethods” in the class where you are going to use it)

Doing this, we would simplify the code we had above to have instead:

var table = new Table();
var row = new Row();
row.CreateAndAddCell("test1");
row.CreateAndAddCell("test2");
table.Rows.Add(row);

This looks nicer than before, but we could still improve it a little bit if we would also add an extension to the Table class using params.

public static class MyExtensionMethods
{
   public static void CreateRowWithColumns(this Table table, params string[] texts)
   {
      var row = new TableRow();
      foreach (var text in texts)
      {
         row.CreateAndAddCell(text);
      }
      table.Rows.Add(row);
   }

   public static void CreateAndAddCell(this TableRow row, string text)
   {
      row.Cells.Add(new TableCell { Text = text });
   }
} 

Doing this, we could change our previous code to a cleaner one:

var table = new Table();
table.CreateRowWithColumns("test1", "test2");

Great difference, isn’t it? Now we could re-use this code any time that we need to create a Table with text columns! I hope you found it interesting!

Here you have the fiddle in case you want to play around:

For more information: https://msdn.microsoft.com/en-CA/library/bb383977.aspx

Please follow:
CategoriesC#

One Reply to “Extension Methods in C#”

Comments are closed.