184

Is there any way I can add a static extension method to a class.

specifically I want to overload Boolean.Parse to allow an int argument.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Midhat
  • 17,454
  • 22
  • 87
  • 114
  • 26
    how can this be a duplicate? This wants to add an extension method that behaves like a static (class) method to a class that can have instances like Boolean, whereas the other question asks how to add an extension method to a static class – George Birbilis Nov 28 '15 at 21:14
  • 1
    it would be nice if C# supported syntax like: "public static DependencyProperty Register(static DependencyProperty x, string name, Type propertyType, Type ownerType, FrameworkPropertyMetadata typeMetadata)", so that I could use it in Silverlight to achieve compatibility with WPF syntax (to wrap Dr.WPF's implementation of value coercion for DependencyProperty). Note the "static DependencyProperty" parameter instead of the "this DependencyProperty" one (alternatively instead of static maybe they could use other keyword like type or typeof) – George Birbilis Nov 28 '15 at 22:58
  • Same problem with `Enum.Parse` with providing a string. Extending a string unfortunately isnt as obvious as extending an int is. C# is missing syntax! – C4d Aug 18 '16 at 14:18
  • I think this will be accomplishable by Shapes in an upcoming C# spec – Sinaesthetic Sep 16 '18 at 18:52
  • It doesn't look like you can. [See here for a discussion on it](http://social.msdn.microsoft.com/Forums/en-US/vcsharp2008prerelease/thread/c0884849-c10c-49b8-9ea4-5ca1d723576e) I would very much like to be proven wrong though. – Ray May 15 '09 at 04:03
  • Here is the [feature request](https://github.com/dotnet/csharplang/discussions/2505). Please upvote it. – Kiruahxh Feb 25 '21 at 09:11

3 Answers3

174

In short, no, you can't.

Long answer, extension methods are just syntactic sugar. IE:

If you have an extension method on string let's say:

public static string SomeStringExtension(this string s)
{
   //whatever..
}

When you then call it:

myString.SomeStringExtension();

The compiler just turns it into:

ExtensionClass.SomeStringExtension(myString);

So as you can see, there's no way to do that for static methods.

And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:

Bool.Parse(..)

vs.

Helper.ParseBool(..);

Doesn't really bring much to the table...

BFree
  • 102,548
  • 21
  • 159
  • 201
  • 264
    *what would really be the point of being able to add static methods on existing classes?* I've wanted to do this repeatedly in many cases. My reasoning is: I want to extend `String.Reconvert` as an extension method. I could write `Helper.ReconvertString`, but using Visual Studio and auto-complete, my co-workers wouldn't look under `Helper`. They would look for a `String` method, and not finding one, likely go and re-invent the wheel. – abelenky Oct 30 '13 at 16:15
  • 154
    I completely disagree, the benefit of it would be the same benefit that instanced extension methods provide. I could also use helper classes to serve the same purpose as the normal extension methods, but why should I when the extension approach is far more elegant to work with. Syntactic sugar is useful, be it instanced or static. – WiredWiz Nov 07 '13 at 15:46
  • 54
    I think they would bring just as much to the table as far as syntactic sugar goes. It's about accessibility and things being where you expect them to be in popular classes, rather than in obscure helpers. For example an extension method like DateTime.FromNanoseconds would be helpful, or DateTime.FromSecondsSinceEpoch. These don't make sense as instance method, since they are essentially constructors, yet they would be easy to find as as static extension methods. The reason is that the framework classes are simply incomplete, and extension methods are a workaround for completing them. – Triynko Nov 26 '13 at 15:00
  • 31
    @Triynko is right. In the example above, where and what is the **Helper** class? How would one know where to find it and what namespace is it in? For these reasons, extensions which appear where you **expect** them to, is a useful feature. – mungflesh Aug 13 '14 at 13:01
  • 1
    There's a reason you have the `string.Join` method instead of a separate StringHelpers class in the framework. That said however, I hate when I'm expecting an extension method and have to go hunt for the right namespace to add. At least with classes I can right-click and resolve to add the `using`. – Jason Goemaat Mar 03 '15 at 05:31
  • 4
    I'm thinking that this answer could just be edited down to "No", since this is only a matter of language design. There is nothing in the rest of the answer that shows any conflicts in implementing static extension methods in the language. – Alex Sep 05 '15 at 14:50
  • For instance right now I'm writing helper methods for Console to make it easier to output colors and change cursor positions so I can easily do things like live updates without writing extra lines, and output something in a certain color without "getting current color/setting new color/writing output/setting color back to original color". It would be nice to be able to add them to Console, but I'll probably re-implement Write and WriteLine in my class so the same class can be used for all output. – Jason Goemaat Dec 05 '15 at 10:03
  • 3
    I can think of a good example where you'd want static extension methods. Even the `Int32` class provides `Parse(String)`, `Parse(String, IFormatProvider)`, `Parse(String, NumberStyles)`, `Parse(String, NumberStyles, IFormatProvider)` overloads but the `Boolean` class provides only `Parse(String)`. Wouldn't it be super nice to have even just a `Bool.Parse(String, IFormatProvider)` overload so that you can translate true/false values from other languages? e.g. Cierto/Falso (Spanish), Vrai/Faux (French) and Правда/Ложь (Russian)? – AlwaysLearning Jan 13 '16 at 03:16
  • I'm not against static extensions, but one reason you might not want to extend a common CLR class is while it makes the extension easy to find, it may suggest to the developer that the extension is actually part of the original class. The developer may try to use the extension on another project and then be confused they can't find it. Swings and roundabouts perhaps. – tjmoore Apr 19 '16 at 14:22
  • `StringExtensions.Reconvert(...)` -- *bam*, problem solved in a meaningful way that is **readable, unambiguous, reasonable, and works well with IntelliSense**. It also allows you to place both instance extension methods and static extension methods as such on one class. – John Weisz Jun 09 '16 at 08:39
  • 2
    @JohnWhite Clearly you haven't read top comments below this question :) – Episodex Aug 17 '16 at 12:18
  • 1
    @Episodex I did, hence my suggestion which is standardizable across entire projects in a meaningful way. Just include it in the specs/guidelines that static extension method classes are _always_ in the form of `*Extensions`. It's also much more straightforward than `Helpers`, to the extent it can be considered a whole another approach -- when you are looking for a static method on `String`, you'll begin by typing `Str...`, at which point the `StringExtensions` static class should be already on the list of suggested autocompletion words, its name clearly indicating its intent. – John Weisz Aug 17 '16 at 14:50
  • @JohnWhite Ok, now I see your reasoning. Indeed it's probably the best solution until (ever?) static extensions are implemented in C#. – Episodex Aug 18 '16 at 06:11
  • Extension methods require the this-parameter to be non-null. A way around this would be to write a static method which could have any or all parameters null without throwing an exception. I don't own the source code to HashSet, so I can't fix this shortcoming of UnionWith(). If I could fix it, I would want to write a static extension method. Since that is not possible, I now have to write a local private method and put it in a gist. – philologon Nov 02 '17 at 22:16
  • 1
    Downvoted because: "what would really be the point of being able to add static methods on existing classes?". I'm coming from other languages and experiment with C#, and so far a major pain point is to be not able to extend existing nominal types with static methods. Examples: `Assert.Fail()`, `var duration = TimeSpan.Seconds(1.2)`, etc., etc., etc. ... – CouchDeveloper Jan 21 '23 at 12:39
94

specifically I want to overload Boolean.Parse to allow an int argument.

Would an extension for int work?

public static bool ToBoolean(this int source){
    // do it
    // return it
}

Then you can call it like this:

int x = 1;

bool y = x.ToBoolean();
Neuron
  • 5,141
  • 5
  • 38
  • 59
bsneeze
  • 4,369
  • 25
  • 20
  • 26
    +1 for creativity. You didn't answer his question but I believe you found the most elegant solution. Especially considering that literally to "parse" means to analyze a _string_ :) (see [definition](http://en.wikipedia.org/wiki/Parsing)) – tsemer Sep 18 '12 at 13:59
  • 1
    Don't forget, int is a value Type. You need to usig it as @bsneeze `y=x.ToBoolean()` has written, because in extension Methods for Value Types, the values are **NOT** beeing passed by reference. – LuckyLikey Jun 10 '15 at 14:26
-15

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();
BobbyShaftoe
  • 28,337
  • 7
  • 52
  • 74