I would like to override bool
's TryParse
method to accept "yes" and "no." I know the method I want to use (below) but I don't know how to override bool
's method.
... bool TryParse(string value, out bool result)
{
if (value == "yes")
{
result = true;
return true;
}
else if (value == "no")
{
result = false;
return true;
}
else
{
return bool.TryParse(value, result);
}
}
You can't override a static method. You could however create an extension method.
public static bool TryParse(this string value, out bool result)
{
// For a case-insensitive compare, I recommend using
// "yes".Equals(value, StringComparison.OrdinalIgnoreCase);
if (value == "yes")
{
result = true;
return true;
}
if (value == "no")
{
result = false;
return true;
}
return bool.TryParse(value, out result);
}
Put this in a static class, and call your code like this:
string a = "yes";
bool isTrue;
bool canParse = a.TryParse(out isTrue);
TryParse
is a static method. You can't override a static method.
TryParse
is a static method and you can't override static methods.
You could always try to create an extension method for strings to do what you want:
public static bool ParseYesNo(this string str, out bool val)
{
if(str.ToLowerInvariant() == "yes")
{
val = true;
return true;
}
else if (str.ToLowerInvariant() == "no")
{
val = false;
return true;
}
return bool.TryParse(str, out val);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With