Return False if the variable is not logical

How can I return the code Falseif usable- this is something other than True(something other than bool), currently my code throws an exception. usablenot a bool.

if (!Boolean.Parse(readValue("Useable"))) return true;
return (defined.ContainsKey(key) || (key == "Useable"));
+3
source share
5 answers
bool isUseable;
bool.TryParse(readValue("Useable"), out isUseable);
+12
source

This is the easiest and fastest approach:

return "True".Equals(readValue("Useable"), StringComparison.OrdinalIgnoreCase);

Note. Boolean.TryParseis not a good choice as it is much slower than a simple string comparison. Please view the results of this test (using Jon Skeet BenchmarkHelper) :

using System;
using BenchmarkHelper;

class Example
{
    static void Main()
    {
        var results = TestSuite.Create
                ("Boolean.TryParse vs. String comparison", "True", true)
            .Add(tryParse)
            .Add(stringComparison)
            .RunTests()
            .ScaleByBest(ScalingMode.VaryDuration);

        results.Display(ResultColumns.NameAndDuration | ResultColumns.Score,
                results.FindBest());        
    }

    static Boolean tryParse(String input)
    {
        Boolean result;
        Boolean.TryParse(input, out result);
        return result;
    }

    static Boolean stringComparison(String input)
    {
        return "True".Equals(input, StringComparison.OrdinalIgnoreCase); 
    }
}

Output:

============ Boolean.TryParse vs. String comparison ============
tryParse         12.118 6.03
stringComparison 21.895 1.00
+7
source
bool isUseable;
if (bool.TryParse(readValue("Useable"), out isUseable))
    return isUseable;
return false;
+5

:

return (readValue("Useable") == "TRUE");

EDITED

+1
var result = Equals(true, myobject);
0
source

Source: https://habr.com/ru/post/1718372/


All Articles