The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  83 Posts :: 0 Stories :: 57 Comments :: 2 Trackbacks

Ads

 

Donate via PayPal...

...if you feel the site helped.

Archives

Post Categories

Open Source Projects

Other Blogs

Extension methods were introduced in Visual Studio 2008 as a way of extending functionality on existing classes (included sealed classes). This is particularly useful for adding methods to existing classes that you don’t necessarily want to inherit/extend for a single method, or you can’t inherit because they’re sealed. I’ve made use of the “inheritance chain” function before, which I originally found here.
Now that the new VS2008 is out, I decided to make a minor alteration to make it an extension method, and now all my classes have a method called “InheritanceChain” which outputs the chain to the debug window.
To make an extension method, the “this” keyword was introduced as new parameter option. As you’ll see in the code below, the syntax is slightly different to what you’d usually expect to encounter. The “this” keyword is what turns this into an extension method. If you wanted the method to take a parameter, you’d add them as parameters like normal, just making sure that the “this” parameter is first.
    public static void InheritanceChain(this Type type)

I've included the code for the whole class here - paste it into a new file in your project to make use of it.
static class ExtensionMethods  
    {
        public static void InheritanceChain(this Type type)
        {
            if (type != null)
            {
                InheritanceChain(type.BaseType);
                Console.WriteLine(type.ToString());
            }
 
        }
    }
 
 Some other ideas for extensions methods are (hold your breath, VB guys) - Adding a Left and Right function to the string class :)
 
posted on Friday, December 07, 2007 2:57 PM
Comments have been closed on this topic.