dot net miscellany

Extending Object!

Ever wanted to add your own methods to Object...or any other type for that matter?

I've recently started playing around with Extension methods in C# and they're pretty damn cool.

To add your own method to a Type:

  1. First create a static class, and inside it make a static method with your chosen method signature. The important thing to note is that the method takes as an argument 'this object obj'. This tells the compiler that this method should be callable from type 'object'. The 'this' keyword is a little confusing but it is really to differntiate the argument from a regular static method which accepts an object arg

    My method 'SayHello' simply returns the string "Hello Joe" - a trivial and narcissistic example :)






  2. Now if you create any instance of the object type in your code (the namespace that hosts your extension method must be imported) the SayHello() extension method is available!

    It is also included in every derived type - which in .NET is every single type! (e.g. Int32)

 



This is about as trivial an example as you are likely to find on extension methods but they can be extremely useful - for example, the whole LINQ infastructure is made with extension methods.

 Enjoy

 

Published Thursday, February 19, 2009 8:44 AM by JoE
Filed under: , ,

Attachment(s): 8-2.png

Comments

 

Click & Solve » Extending Object! said:

February 19, 2009 4:35 AM
 

JoE said:

"Do you know the rationale behind the feature in your extend object post? Wouldn't you just have static methods in yr namespace?"

re: andy

I guess my example was pretty pointless and yes you can implement most extension methods as static methods, but extnsion methods complement OOP languages and IMO produce a better design in the end (inheritence etc).

Also, the ability to create extension methods ontop of a library and then distribute your library to others means they are unaware of the implementation of the new, cool, useful method - abstraction baby!

July 14, 2009 10:12 AM
Anonymous comments are disabled

About JoE

.

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker