简体   繁体   中英

Application of TryParse in C#

When 'val' below is not a bool I get an exception, I believe I can use TryParse but I'm not sure how best to use it with my code below. Can anyone help?

checkBox.Checked = Convert.ToBoolean(val);

Thanks

The code is as follows to determine whether the string val is a valid Boolean value and use it to set the Checked property if so. You need to decide what action you would take if it does not represent a valid value.

bool result;
if (bool.TryParse(val, out result))
{
    // val does represent a Boolean
    checkBox.Checked = result;
}
else
{
    // val does not represent a Boolean
}

Assuming that if its not a valid boolean, you don't want it checked:

bool result = false;
bool.TryParse(val, out result);
checkBox.Checked = result;
bool z = false;
if(Boolean.TryParse(val, out z))
{
  checkBox.Checked = z;
}

Just a note: Parse and convert are different operations and may lead to different results.

bool isBool = false;

bool.TryParse( val, ref isBool );

if( isBool )    
{
   ///ok;

}
else
{
  // fail;
}

Well it depends; if you want checkBox.Checked to be equal to true if val - if it is a string - parses to true then use the following:-

bool output;
checkBox.Checked = bool.TryParse(val, out output) && output;

If bool is not a string then you need to decide how to deal with it depending on its type, eg:-

checkBox.Checked = val != 0; 

etc.

Good answers here already.

I will however add, do be careful with TryParse, because contrary to what its name indicates, it can infact still throw an ArgumentException!

That's one of my pet annoyances with .NET! :)

FWIW, the following may also come in handy in this (or similar) cases...

bool myBool = val ?? false;

...which is the good old "null-coalescing operator" and quite nice.

Read more about it here if you are interested: http://msdn.microsoft.com/en-us/library/ms173224.aspx

Just posted this same snippet for another question, but here is the code I use across projects for doing a much better job of handling booleans in all their assorted versions:

bool shouldCheck;
TryParseBool(val, out shouldCheck);
checkBox.Checked = shouldCheck;

/// <summary>
/// Legal values: Case insensitive strings TRUE/FALSE, T/F, YES/NO, Y/N, numbers (0 => false, non-zero => true)
/// Similar to "bool.TryParse(string text, out bool)" except that it handles values other than 'true'/'false'
/// </summary>
public static bool TryParseBool(object inVal, out bool retVal)
{
    // There are a couple of built-in ways to convert values to boolean, but unfortunately they skip things like YES/NO, 1/0, T/F
    //bool.TryParse(string, out bool retVal) (.NET 4.0 Only); Convert.ToBoolean(object) (requires try/catch)
    inVal = (inVal ?? "").ToString().Trim().ToUpper();
    switch ((string)inVal)
    {
        case "TRUE":
        case "T":
        case "YES":
        case "Y":
            retVal = true;
            return true;
        case "FALSE":
        case "F":
        case "NO":
        case "N":
            retVal = false;
            return true;
        default:
            // If value can be parsed as a number, 0==false, non-zero==true (old C/C++ usage)
            double number;
            if (double.TryParse((string)inVal, out number))
            {
                retVal = (number != 0);
                return true;
            }
            // If not a valid value for conversion, return false (not parsed)
            retVal = false;
            return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM