Static extension methods

C#Extension Methods

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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...

Solution 2 - C#

> 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();

Solution 3 - C#

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMidhatView Question on Stackoverflow
Solution 1 - C#BFreeView Answer on Stackoverflow
Solution 2 - C#bsneezeView Answer on Stackoverflow
Solution 3 - C#BobbyShaftoeView Answer on Stackoverflow