× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Creating Extension Methods in C#

Jacob Heater
Nov 12, 2016
<p>Extension methods are one of the neatest features of C#, and in my humble opinion, one of the driving factors behind why I prefer C# over Java. This article is intended to give you a brief overview of how to create extension methods in C# and what extension methods have to offer.</p> <p>Extension methods make it very easy to extend your classes without having to modify the source code for the class. That can be especially useful for when you don't have access to the source code, but you think there would be a really neat feature that you would like to add to the class. For our example, let's add a .Format() to the String class.</p> <pre><code class="language-cs">using System; namespace StringExtensions { //Extension methods have to reside in static classes. public static class ExtString { //Extension methods have to be static, because they reside //in static classes. Also, take note of the first parameter. //{this string s} Extension methods must be written in such a way //that the name of the type you're extending is the first parameter. //You must put the extended type as this {type name} t. public static string format(this string s, params object[] args) { return String.format(s, args); } } }</code></pre> <p>We've written our extendsion method above. We have now extended the string class. I have intentionally left the name of format lower-case because naming the method as Format does not play nicely with the compiler. Let's see how to use our extesnion method below.</p> <pre><code class="language-cs">using System; //We must add a using directive here to import the //namespace under which the extension method lives. using StringExtensions; namespace MyApplication { public class Program { public static void Main(string[] args) { //Now we can use our method to write "Hello, world!" to the console! string message = "{0}, {1}!".format("Hello", "world"); Console.WriteLine(message); Console.ReadLine(); } } }</code></pre> <p>I hope this quick tip on writing extension methods has been useful!</p>
comments powered by Disqus