Static extension methods [duplicate]

放肆的年华 提交于 2019-11-26 18:39:46

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

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

It doesn't look like you can. See here for a discussion on it

I would very much like to be proven wrong though.

You could add an extension method to int

public static class IntExtensions
{
    public static bool Parse(this int value)
    {
        if (value == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public static bool? Parse2(this int value)
    {
        if (value == 0)
        {
            return true;
        }
        if (value == 1)
        {
            return false;
        }
        return null;
    }
}

used like this

        bool bool1 = 0.Parse();
        bool bool2 = 1.Parse();

        bool? bool3 = 0.Parse2();
        bool? bool4 = 1.Parse2();
        bool? bool5 = 3.Parse2();

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!