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.
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.
It doesn't look like you can. See here for a discussion on it
I would very much like to be proven wrong though.
In short, no, you cant.
Long answer, extension methods is 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 benfit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
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();
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();