SHARE
Facebook X Pinterest WhatsApp

.NET Tip: Using Extension Methods

Extension methods allow you to add functionality to existing classes by modifying the original class or using partial classes. In fact, you don’t need access to the source of the class at all. You can extend third-party classes and built-in classes as easily as you can extend your own classes. To demonstrate this, I will […]

Written By
thumbnail
CodeGuru Staff
CodeGuru Staff
Dec 31, 2007
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

Extension methods allow you to add functionality to existing classes by modifying the original class or using partial classes. In fact, you don’t need access to the source of the class at all. You can extend third-party classes and built-in classes as easily as you can extend your own classes. To demonstrate this, I will take the code from a previous tip that uses reflection to display information about an object passed to it and convert it to be an extension method instead. Here is the code for the original DisplayObjectInfo method:

public static string DisplayObjectInfo(Object o)
{
   StringBuilder sb = new StringBuilder();

   // Include the type of the object
   System.Type type = o.GetType();
   sb.Append("Type: " + type.Name);

   // Include information for each Field
   sb.Append("rnrnFields:");
   System.Reflection.FieldInfo[] fi = type.GetFields();
   if (fi.Length > 0)
   {
      foreach (FieldInfo f in fi)
      {
         sb.Append("rn " + f.ToString() + " = " +
                   f.GetValue(o));
      }
   }
   else
      sb.Append("rn None");

   // Include information for each Property
   sb.Append("rnrnProperties:");
   System.Reflection.PropertyInfo[] pi = type.GetProperties();
   if (pi.Length > 0)
   {
      foreach (PropertyInfo p in pi)
      {
         sb.Append("rn " + p.ToString() + " = " +
                   p.GetValue(o, null));
      }
   }
   else
      sb.Append("rn None");

   return sb.ToString();
}

This is how you call the DisplayObjectionInfo method:

GPSLocation Location = new GPSLocation(39, -86, 50, 180);
Debug.Print(Util.DisplayObjectInfo(Location));

And here is the output:

Type: GPSLocation

Fields:
   None

Properties:
   Double Latitude  = 39
   Double Longitude = -86
   Int32 Speed      = 50
   Int32 Direction  = 180

There are only a couple things that you need to do to make this into an extension method. First, all extension methods must be defined in a non-generic static class. Second, your method needs to accept a parameter of the type you want to extend. In this case, I want to extend the object data type, so I simply have to prepend the this keyword before the data type of the parameter to the DisplayObjectInfo function. So, my new definition of DisplayObjectInfo as an extension method looks like this:

public static class Util2008
{
   public static string DisplayObjectInfo(this Object o)
   {
      ...
   }
}

The body of the method does not change at all. Take a look at how you use the new extension method.

GPSLocation Location = new GPSLocation(39, -86, 50, 180);
Debug.Print(Location.DisplayObjectInfo());

Now, instead of passing the Location object to the DisplayObjectInfo method, the method has become a part of the Location class. Extension methods are fully integrated into the development environment. This means that your extension methods will show up with Intellisense. Take time to explore extension methods further to see how you can take best advantage of them in your applications.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.

Recommended for you...

C# vs Java
Nicholas Rini
Mar 24, 2023
C# versus C
Nicholas Rini
Mar 22, 2023
Different Types of JIT Compilers in .NET
Tariq Siddiqui
Mar 17, 2023
Middleware in ASP.NET Core
Tariq Siddiqui
Mar 16, 2023
CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.