tags:

views:

205

answers:

5

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);
    }
}
+1  A: 

This is not possible.

SLaks
+5  A: 

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

John Saunders
Would the best way to do this just be with a helper function of my own, then?
Daniel Rasmussen
Write your own extension method for the string type.
jsmith
+8  A: 

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);
Greg
Personally, I like my Parse methods to return `Nullable<>`, where the return value is `null` if the string can't be parsed. This eliminates the need for an out parameter, and makes for nice calling syntax.e.g. `bool a = "blah".ParseBool() ?? false;`
Greg
`Nullables` are indeed handy for parsing, but I was trying to override the existing `TryParse` method. Now that I'm writing my own, tho, I'll probably do something like that. Also, I am using `StringComparison.OrdinalIgnoreCase` but didn't put it in my example just to make it look cleaner. Finally, why would you label your method 'TryParseBoolean' when your out type is a `bool`? (Though I suppose if you switched to `Nullables`, you'd need that naming.)
Daniel Rasmussen
@cyclotis04 - Good call. Because of the out parameter, the name `TryParse` would indeed be sufficient.
Greg
I might have upvoted this, but I see absolutely no sense in creating an *extension* method (especially on a class as commonly-used as `System.String`) when a simple static method would suffice. It's highly disturbing that everyone else seemed to have the same idea too; there seems to be an ongoing obsession with using extension methods in inappropriate places.
Aaronaught
Does this work? I mean, the signature of the original TryParse method is also "bool TryParse(string, out bool). Does the throw a compiler error or does it shadow the TryParse method?
SchlaWiener
What's less simple about an extension method? Where would you put a static method? The problem I have with static methods is it leads to classes with no purpose other than to hold helper methods which should have been extension methods in the first place.
Daniel Rasmussen
@SchlaWiener - The original `TryParse` is not an extension method, and is defined in a different class. The difference is `bool.TryParse("string", out value)` vs `"string".TryParse(out value)`.
Greg
+3  A: 

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);
}
Justin Niessner
+1 Prefer this as dosn't use out value - just returns result
David Relihan
The problem with this is I'm trying to know if the string is valid boolean - true, false, yes, no, 1, 0. "No" is valid boolean, though it returns false.
Daniel Rasmussen
@cyclotis04 - I updated my answer to better meet your requirements. The extension method now behaves more like bool.TryParse(). Personally, I'm not a big fan out parameters though.
Justin Niessner
+2  A: 

You cannot override TryParse. However, you could create an extension method on string for convenience.

public static class StringExtension
{
    public static bool TryParseToBoolean(this string value, bool acceptYesNo, out bool result)
    {
        if (acceptYesNo)
        {
            string upper = value.ToUpper();
            if (upper == "YES")
            {
                result = true;
                return true;
            }
            if (upper == "NO")
            {
                result = false;
                return true;
            }
        }
        return bool.TryParse(value, out result);
    }
}

And then it would be used like so:

public static class Program
{
    public static void Main(string[] args)
    {
        bool result;
        string value = "yes";
        if (value.TryParseToBoolean(true, out result))
        {
            Console.WriteLine("good input");
        }
        else
        {
            Console.WriteLine("bad input");
        }
    }
}
Brian Gideon
Apparently I'm not the only one to suggest this.
Brian Gideon