C# Extension Methods

Microsoft has added a wonderful new addition to the .Net framework, Extension Methods! Extension methods allow you to add custom methods to already existing types (class) without the need to derive a new type from them or modify them (some of which you can’t such as built in .Net System types i.e. String, Int, Double). How it all works is these newly defined methods attach themselves to the type which they are referncing and can be used as if they are one of the original methods created at its inception. I good example of the perfect implementation of Extension Methods is the new LINQ library which when referenced in your code adds tons of new, fancy methods to collection types which implement the IEnumerable interface (there may be more to it than I have written here, but I am trying to be brief).

In order to set up your own custom Extension Methods within your assembly you need to define a Static Class which will hold all of these methods. Depending on the number of these methods you have for each type you wish to extend you may want to have a seperate Static Class for each of those types containing only the methods for that type. Extension Methods are Static just as the class that holds them.

Here is an example using the default System.String type:

public static class CustomStringExtensions

{
    public static bool ContainsQuestion(this String str)
    {
        return str.Contains('?');
    }
}

Now as long as you reference the assembly which contains this class every String object you use will automatically have the ContainsQuestion method.

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s