Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override TryParse?

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);
    }
}
like image 954
dlras2 Avatar asked Jun 11 '10 14:06

dlras2


3 Answers

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);
like image 109
Greg Avatar answered Oct 18 '22 02:10

Greg


TryParse is a static method. You can't override a static method.

like image 5
John Saunders Avatar answered Oct 18 '22 00:10

John Saunders


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);
}
like image 3
Justin Niessner Avatar answered Oct 18 '22 02:10

Justin Niessner