tags:

views:

430

answers:

5

How can I the code below to return False if usable is anything other than True (anything other than bool), currently my code throws an exception usable is not a bool.

if (!Boolean.Parse(readValue("Useable"))) return true;
return (defined.ContainsKey(key) || (key == "Useable"));
A: 
var result = Equals(true, myobject);
leppie
Does this work if `myObject` is the string `True`?
Drew Noakes
+12  A: 
bool isUseable;
bool.TryParse(readValue("Useable"), out isUseable);

HTH, Kent

Kent Boogaart
Should be bool.TryParse(readValue("Useable"), out isTrue), but otherwise I would do it the same way.
rslite
+1 Whoops, reposted this, but deleted.
Kyle Rozendo
There's no point initialising `isUseable` in this code. You can remove the assignment -- it's misleading.
Drew Noakes
@Drew: not sure about "misleading". If anything, it's more explicit, but perhaps superfluous. I've removed it.
Kent Boogaart
`Boolean.TryParse` is much slower than a simple string comparison - please see my answer.
Andrew Hare
@Andrew: looking at Boolean.TryParse in reflector, it does exactly the same string comparison you're doing, so I have to question your benchmark results.
Kent Boogaart
@Kent -- I chose the word misleading because it implies (perhaps to a more novice programmer) that the value specified in the initialiser remains if the parse fails. Consider the scenario that you'd initialised it to `true` instead. I've debugged errors in other people's code due to this on a few occasions, which is why I mention it.
Drew Noakes
+1  A: 

How about:

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

EDITED as a result of Drew's comment

Lazarus
Why do you need `? true : false` in this code?
Drew Noakes
That's a very good point Drew... answering in the middle of other things!
Lazarus
You might also use string.Equals(readValue("Useable"), "TRUE", StringComparison.OrdinalIgnoreCase) as the poster doesn't indicate what case the return value would be. Ordinal comparisons are faster too.
Drew Noakes
+5  A: 
bool isUseable;
if (bool.TryParse(readValue("Useable"), out isUseable))
    return isUseable;
return false;
JDunkerley
You could shorten this code to: `return bool.TryParse(readValue("Useable"), out isUseable) ` ...personally I find that more readable.
Drew Noakes
+7  A: 

This is the simplest and fastest approach:

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

Note: Boolean.TryParse is not a good choice as it is significantly slower than a simple string comparison. Please see the results of this test (using Jon Skeet's 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
Andrew Hare
+1 There's no need to do parsing here (if I understand the original question correctly). With this snippet, I would probably invert the syntax so there isn't a function call on a string literal, though.
Jon Seigel
Possibly a stupid question but what is the unit of the time value? Is seems that stringComparison uses more time than tryParse or am I reading this wrong?
Lazarus
@Jon - What's wrong with a method call on a string literal? If you inverted the syntax you could potentially end up with a `NullReferenceException` if the result of `readValue("Useable")` was `null`.
Andrew Hare
@Lazarus - Not a stupid question at all. From http://msmvps.com/blogs/jon_skeet/archive/2009/01/26/benchmarking-made-easy.aspx: "A benchmark result has a duration and an iteration count, as well as the descriptive name of the test which was run to produce the result. Results can be scaled so that either the duration or the iteration count matches another result. Likewise a result has a score, which is simply the duration (in ticks, but it's pretty arbitrary) divided by the iteration count...
Andrew Hare
... Again, the score can be retrieved in a scaled fashion, using a specified result as a "standard" with a scaled score of 1.0. Lower is always better."
Andrew Hare
I have to question this benchmark. Crack open reflector and look at Boolean.TryParse. It does exactly that string comparison logic for you.
Kent Boogaart
@Kent - Very interesting! I will have to re-evaluate this!
Andrew Hare
It's a nice, concise solution regardless.
Lazarus
tsk tskm, magic constants. That's what Boolean.TrueString is for.
ICR
@ICR - well played!
Andrew Hare