views:

169

answers:

3

I have recently started to make useful use of C# extension methods. The SO examples and the documentation suggest that they are only used for instance methods (i.e. with the this keyword). It is possible to use them (or another approach) with static/class methods?

(My particular requirement is converting Java code to C# where "most of the code" does not need editing. The Java instance methods (e.g. Java String.indexOf()) can be routed through an extension method calling C# string.IndexOf()). I would like to do the same for, say, Java Math.abs() => C# Math.Abs()).

SUMMARY No. The answers suggest it would be a reasonable thing to have but it's unlikely to happen soon. Workarounds will require editing creating new classes or something similar and may not be worth it.

+3  A: 

You cannot create static extension methods - it's also something I've wished to be able to do!

You could create your own static classes with a standard suffix, i.e. MathJSyntax.abs(..) which would call Math.Abs(..)

frou
@frou. Thanks. I am, actually, creating a set of my own classes because I may have to go the otehr way as well. The extension classes just make it invisible!
peter.murray.rust
The only problem you should encounter with this is if there is an existing .net class/method of the same name that doesn't provide the implementation you need. But that should be fairly rare.
Jason Williams
A: 

The notation itself doesn't let you do it, the "this" class parameter expects an instance to the class to be passed in. If they intended to at least eventually add it, they wouldn't have written it like that.

So the short answer is nope, and never will be!

Blindy
+1  A: 

C# 3.0 does not allow the creation of static extension methods, unfortunately. F# however does allow this, along with the much desired feature of extension properties.

Noldorin
Regarding Extension properties, I think Eric Lippert's recent post is quite interesting: http://blogs.msdn.com/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx
flq
Yeah... I still think it's a shame it wasn't implemented.
Noldorin