• The Nerve (unregistered)

    Fixed?

    // "true" or "false"
    public static string Bool2Str(bool b)
    {
        return b ? System.Boolean.TrueString : System.Boolean.FalseString;
    }
    
  • Larry (unregistered)

    TRWTF is that C-Pound allows you to use a bool in a switch statement.

  • Keith Williams (unregistered) in reply to The Nerve
    
    ///
    ///Do not use.  Kept only in case [Programmer's name here] was dumb enough to use reflection
    ///
    [Obsolete]
    public static string Bool2Str(bool b)
    
    {
       return b.ToString();
    }
    
    
  • anon (unregistered)
    // "true" or "false"
    
    public static string Bool2Str(bool b) {
        return b.toString();
    }
    
  • TheCPUWizard (unregistered) in reply to Larry

    Actually C# allows you to switch on anything that is equatible (e.g. strings). For non-integral (or low density integral) this gets implemented as a chain of is/else if/else if/ else. Many developers find the swtich syntax easier to follow than having to match up the if statements.

  • (cs)

    C# fun facts: Boolean keywords are all lowercase. ToString() and TrueString/FalseString are capitalized. Parse() expects capitalization.

    This method will not return "true" or "false" as is.

  • bool b (unregistered)

    I think this warrants an extension method:

    public static string Bool2Str(this bool b){return b.ToString();}

  • (cs) in reply to TheCPUWizard
    TheCPUWizard:
    Actually C# allows you to switch on anything that is equatiblep (e.g. strings). For non-integral (or low density integral) this gets implemented as a chain of is/else if/else if/ else. Many developers find the swtich syntax easier to follow than having to match up the if statements.

    I believe the word you're looking for is comparable. And I love being able to switch() on strings, something that Java sadly lacks.

    frits:
    C# fun facts: Boolean keywords are all lowercase. ToString() and TrueString/FalseString are capitalized. Parse() expects capitalization.

    This method will not return "true" or "false" as is.

    Hahaha, missed that one. The guy who wrote this code was not only a tool, he evidently never tested it either.

  • (cs) in reply to The Nerve
    The Nerve:
    Fixed?
    // "true" or "false"
    public static string Bool2Str(bool b)
    {
        return b ? System.Boolean.TrueString : System.Boolean.FalseString;
    }
    

    As usual, the answer is no. This returns "True" or "False".

  • The Nerve (unregistered)

    Fixed (in more ways than one)

    /**
     * @return "true" or "false"
     */
    public static String bool2Str(boolean b) {
        return Boolean.valueOf(b).toString();
    }
    
  • verto (unregistered)

    I'm glad Alex reminded us of that previous article with FILE_NOT_FOUND. I had almost forgotten about it since yesterday.

  • Koppernicus (unregistered)

    I for one am glad that the original programmer decided to future proof his code, so that when the new Tri-State boolean is introduced in C# 13.0, his code will detect the change and blow up instead of failing silently.

  • (cs) in reply to Koppernicus
    Koppernicus:
    I for one am glad that the original programmer decided to future proof his code, so that when the new Tri-State boolean is introduced in C# 13.0, his code will detect the change and blow up instead of failing silently.

    C# already has a tri-state boolean type - nullable booleans.

  • Anonymous (unregistered)

    Anyone who works with C# or Java should know that the ToString method lives at the root of the type hierarchy. However, this is hardly a major WTF. An unnecessary switch is not the end of the world, it's not like he reflected on the type or anything retarded like that.

    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

  • Steenbergh (unregistered)

    Aargh! I HATE conversion functions with a literal '2' between the one datatype and the other. It just seems so unprofessional.

  • VJ (unregistered)

    he missed some cases:

    // "true" or "false" public static string Bool2Str(bool b) { switch(b) { case true: return System.Boolean.TrueString; case false: return System.Boolean.FalseString; case 1: return "1"; case 2: return "2"; case 0: return "0"; case "abc": return "ops"; default: return "error"; } }

  • Mad Adder (unregistered)

    I know this is low hanging fruit as it's all but spelled out in the article, but here's my take on the CodeSOD.

    public static string Bool2Str(bool b)
    {
        switch(b)
        {
            case true:
                return System.Boolean.TrueString;
            case false:
                return System.Boolean.FalseString;
            default:
                return "FILE_NOT_FOUND";
        }
    }
    

    suscipit: The coffee is too hot to gulp, suscipit (so sip it).

  • DT (unregistered) in reply to Anonymous
    Anonymous:
    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

    At some point I was tought that all switches should have a default statement. Maybe the same goes for the author, don't blame a guy for paying attention in class.

  • Corey (unregistered) in reply to verto
    verto:
    I'm glad Alex reminded us of that previous article with FILE_NOT_FOUND. I had almost forgotten about it since yesterday.

    I think that was a preemptive FILE_NOT_FOUND. You know, to keep the "what about FILE_NOT_FOUND dumb-asses quiet."

  • jumentum (unregistered) in reply to Anonymous
    Anonymous:
    Anyone who works with C# or Java should know that the ToString method lives at the root of the type hierarchy. However, this is hardly a major WTF. An unnecessary switch is not the end of the world, it's not like he reflected on the type or anything retarded like that.

    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

    There is no Object.ToString() method in Java.

  • Community of Realists Against Psuedo-nulls (CRAP) (unregistered)

    Can someone explain to me why for enums (not limited to booleans here) some programmers like putting a "default" or "unknown" value which is, by all accounts, a pseudo-null as it designed to not be a valid option and usually never fully implemented. So now we lucky folks trying to maintain the enums have to check for both null and pseudo-null. As if null and empty-string double-checks weren't annoying enough.

  • Matt Westwood (unregistered) in reply to jumentum
    jumentum:
    Anonymous:
    Anyone who works with C# or Java should know that the ToString method lives at the root of the type hierarchy. However, this is hardly a major WTF. An unnecessary switch is not the end of the world, it's not like he reflected on the type or anything retarded like that.

    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

    There is no Object.ToString() method in Java.

    No, it starts with a lowercase letter.

    CAPTCHA: Mara. Naah, not t'day.

  • (cs) in reply to Community of Realists Against Psuedo-nulls (CRAP)
    Community of Realists Against Psuedo-nulls (CRAP):
    Can someone explain to me why for enums (not limited to booleans here) some programmers like putting a "default" or "unknown" value which is, by all accounts, a pseudo-null as it designed to not be a valid option and usually never fully implemented. So now we lucky folks trying to maintain the enums have to check for both null and pseudo-null. As if null and empty-string double-checks weren't annoying enough.

    I like to put a default block in switch statements that handle enums that throws an exception with a message detailing that the enum value isn't recognized and where in code the problem is. That way, if in the future someone adds values to the enum but doesn't update the other code, it'll throw an exception and hopefully it'll get noticed during testing.

    Adding a 'Default' value to the enum, however, is stupid. Any value of the enum should be usable and valid.

  • (cs)
    Apparently, the guy who wrote this didn't stay on the job long enough to actually use it.

    Writing code like that, I wonder why?

  • enim (unregistered)

    Serious question: is bool an object in C#?

    Now I have to hope and prey this comment doesn't get deleted by the over-zealous moderators. I wonder at the motivation behind the recent police effort.

  • Anonymous (unregistered) in reply to DT
    DT:
    Anonymous:
    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

    At some point I was tought that all switches should have a default statement. Maybe the same goes for the author, don't blame a guy for paying attention in class.

    So you do this:

    case true:
    {
      // Do whatever for true case
    }
    case default:
    {
      // Do whatever for false case
    }
    

    Now you've satisfied your school teacher by providing a default for the case, but you don't have a useless branch that never gets called. Simple.

  • (cs) in reply to enim
    enim:
    Serious question: is bool an object in C#?

    Now I have to hope and prey this comment doesn't get deleted by the over-zealous moderators. I wonder at the motivation behind the recent police effort.

    Serious question: Does the internet not work for you? This question can be answered doing a minimal amount of research. Alternatively, you could troll over at codeproject.com/stackoverflow.com to get the answer.

  • Hypersw (unregistered)

    Well, by lack of expertise you might consider that this function is actually useless.

    However, it is quite possible to make it yield "error" if you pass in a boolean value converted from an integer 2 (or any other integer except zero or one).

    Or did you think boolean is just about "false" or "true" constants? It's an integer after all, just with special semantic.

    A working sample:

    private static unsafe void Main() {   bool val;   ((byte)&val) = 2;   Console.WriteLine(Bool2Str(val)); }

    public static string Bool2Str(bool b) {   switch (b)   {     case true:       return System.Boolean.TrueString;     case false:       return System.Boolean.FalseString;     default:       return "error";   } }

    Of course it's not reasonable in pure C#, but should you be interoperating with some legacy C++ components...

  • Anonymous (unregistered) in reply to jumentum
    jumentum:
    Anonymous:
    Anyone who works with C# or Java should know that the ToString method lives at the root of the type hierarchy. However, this is hardly a major WTF. An unnecessary switch is not the end of the world, it's not like he reflected on the type or anything retarded like that.

    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

    There is no Object.ToString() method in Java.
    Yes there is, it's just capitalized differently. Don't be pedantic!

  • Anonymous (unregistered) in reply to enim
    enim:
    Serious question: is bool an object in C#?

    Now I have to hope and prey this comment doesn't get deleted by the over-zealous moderators. I wonder at the motivation behind the recent police effort.

    Everything is an object in C#. "Object" is the root of the type hierarchy so everything, including primatives, ultimately derives from it. So to answer your question, yes, a bool is an object in C#. Hope you read this before it gets moderated!

  • (cs) in reply to Hypersw
    Hypersw:
    Well, by lack of expertise you might consider that this function is actually useless.

    However, it is quite possible to make it yield "error" if you pass in a boolean value converted from an integer 2 (or any other integer except zero or one).

    Or did you think boolean is just about "false" or "true" constants? It's an integer after all, just with special semantic.

    A working sample:

    private static unsafe void Main() {   bool val;   ((byte)&val) = 2;   Console.WriteLine(Bool2Str(val)); }

    public static string Bool2Str(bool b) {   switch (b)   {     case true:       return System.Boolean.TrueString;     case false:       return System.Boolean.FalseString;     default:       return "error";   } }

    Of course it's not reasonable in pure C#, but should you be interoperating with some legacy C++ components...

    I don't think this is a good test either. bool will evaluate to either true or false, so even if you didn't marshal a win32 BOOL or some other value correctly, it simply will take the bit value at a location. There is no 'third' or other state.

    More than likely, if there is an error, it will evaluate to true, since anything other than 0 will convert to true.

  • (cs)

    I present this abomination. Feel free to modify and add even more WTF to the below code.

    public interface IBoolVal { String StringRep(); }

    public class FalseBool : IBoolVal
    {
        string IBoolVal.StringRep()
        {
            return "False";
        }
    }
    
    public class TrueBool : IBoolVal
    {
        string IBoolVal.StringRep()
        {
            return "True";
        }
    }
    
    public class BoolHelper : System.Object
    {
        public static bool ConvertStringToBool(string value)
        {
            string sTrue = ConvertBoolToString(true).ToLower();
            string sFalse = ConvertBoolToString(false).ToLower();
    
            if (sTrue == value.ToLower())
                return true;
            else 
                return false;
        }
        public static string ConvertBoolToString(bool value)
        {
            IBoolVal v;
            if (value) v = new TrueBool(); else  v = new FalseBool();
            return v.StringRep();
        }
    }
    
  • (cs) in reply to ObiWayneKenobi
    ObiWayneKenobi:
    Apparently, the guy who wrote this didn't stay on the job long enough to actually use it.
    Writing code like that, I wonder why?
    No you don't. You don't wonder at all, you big liar.
  • (cs)

    The existence of the method certainly isn't dumb. It would allow you to easily internationalize your messages (if they were user-facing) sometime down the road.

    Having the method without using it is dumb. Adding a default case to the switch is dumb.

  • Bobbo (unregistered) in reply to DT
    DT:
    Anonymous:
    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

    At some point I was tought that all switches should have a default statement. Maybe the same goes for the author, don't blame a guy for paying attention in class.

    You'll be pleased to know that the deliberate irony was not missed.

  • jrh (unregistered) in reply to DT
    DT:
    Anonymous:
    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

    At some point I was tought that all switches should have a default statement. Maybe the same goes for the author, don't blame a guy for paying attention in class.

    If if you give this guy the benefit of the doubt and assume he's following the "all case statements need a default" rule, you'd expect his switch to look like this:

    switch(b)
    {
        case true:
            return System.Boolean.TrueString;
        default:
            return System.Boolean.FalseString;
    
    }
    
  • (cs) in reply to jumentum
    jumentum:
    Anonymous:
    Anyone who works with C# or Java should know that the ToString method lives at the root of the type hierarchy.
    There is no Object.ToString() method in Java.

    More importantly, and less nit-pickingly, a boolean is-not-an Object. Though there is already a library function:

    Boolean.toString(someBool)
    Or the lazy man's solution:

    "" + someBool
  • Hypersw (unregistered) in reply to pitchingchris
    pitchingchris:
    I don't think this is a good test either. bool will evaluate to either true or false, so even if you didn't marshal a win32 BOOL or some other value correctly, it simply will take the bit value at a location. There is no 'third' or other state.

    More than likely, if there is an error, it will evaluate to true, since anything other than 0 will convert to true.

    I can imagine cases where functions like this could be put to use, but 99.99% that the one above is not the case. In that I agree.

    The third state appears when you're comparing two true bools which are not quite equally true. Didn't see that other than in proof-of-concept samples, however.

  • Anon (unregistered)

    using System; using System.Collections.Generic; using System.Linq; using System.Text;

    namespace ConsoleApplication15 { class Program { static void Main(string[] args) { Console.WriteLine(Bool2Str(true)); Console.WriteLine(Bool2Str(false));

            unsafe
            {
                bool val;
                *((byte*)&val) = 2;
                Console.WriteLine(Bool2Str(val));
    
                Console.ReadLine();
            }
        }
    
        // "true" or "false"
        public static string Bool2Str(bool b)
        {
            switch (b)
            {
                case true:
                    return System.Boolean.TrueString;
                case false:
                    return System.Boolean.FalseString;
                default:
                    return "error";
            }
        }
    }
    

    }

    Outputs: True False error

    you need to compile with /unsafe switch.

  • Anonymous User (unregistered)

    Is "bool" an object in C#?

    • No, it's a value type.

    Is "Bool" an object in C#?

    • Yes. In fact, I believe it's a 'Boxed' format of bool.

    The main difference between the two is how the data is stored; objects are generally 'like' C++ pointers (with a lot more guards) while value types are generally direct bits of memory. So values can't be 'null', while objects can. This also explains why a C# struct can't be null; it's considered a value-type, if a rather complex one.

    Also, Enums in C# are usually value-types (int by default, unless you override), so they shouldn't be nullable. So, to represent a base/unknown/default state that doesn't match a 'good' state, you would need either another value that you'd always have to check, or initial state of base/unknown/default to do the same thing.

    Bonus points: 'Enum' is its own class type with its own static functions that work nicely with enum types. Take a peek at it, see if any of them might be useful for what you're doing.

  • Squeeself (unregistered) in reply to Community of Realists Against Psuedo-nulls (CRAP)

    String.IsNullOrEmpty() http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx

    This is but one of the many reasons I <3 C#.

  • Jellineck (unregistered) in reply to Larry
    Larry:
    TRWTF is that C-Pound allows you to use a bool in a switch statement.

    I can't wait for someone to call C# 'C-Pound' in an interview.

    Captcha: acsi - how you pronounce ASCII in the ghetto.

  • JayC (unregistered) in reply to jrh
    jrh:
    DT:
    Anonymous:
    But I must say, it's cute how he provided a default path in case the bool evaluates to something other than 'true' or 'false'. You never know!

    At some point I was tought that all switches should have a default statement. Maybe the same goes for the author, don't blame a guy for paying attention in class.

    If if you give this guy the benefit of the doubt and assume he's following the "all case statements need a default" rule, you'd expect his switch to look like this:

    switch(b)
    {
        case true:
            return System.Boolean.TrueString;
        default:
            return System.Boolean.FalseString;
    
    }
    

    C# does some blind execution path checking to see that all execution paths return a value. So not only is he following the "all case statements need a default" rule, in this case the C# compiler will insist on there being an unnecessary default statement or return statement after the case statement.

  • boog (unregistered) in reply to DT
    DT:
    At some point I was tought that all switches should have a default statement. Maybe the same goes for the author, don't blame a guy for paying attention in class.
    Sure, he was paying attention in class. Just not during the lectures on the value range of boolean datatypes, when and when not to use switch statements, and how not to reinvent the language's already-existing library functions.
  • John Preston (unregistered)

    Actually, all .Net languages allow Booleans (and other data types) to have a 3rd (or n+1th) state. Not set. So you may not be able to get FileNotFound, but Not Set is pretty close.

    That leaves you with a Boolean with a 3rd state. So really, more of a Trilean than a Boolean.

    Fun fact, you can never set a variable back to Not Set once it has a value.

  • boog (unregistered) in reply to Jellineck
    Jellineck:
    Larry:
    TRWTF is that C-Pound allows you to use a bool in a switch statement.

    I can't wait for someone to call C# 'C-Pound' in an interview.

    Captcha: acsi - how you pronounce ASCII in the ghetto.

    Looks like this guy beat you to it:

    http://thedailywtf.com/Articles/5_years_C-pound_experience.aspx

    (Sorry the link isn't clickable; I put [url] tags around it, but Akismet says that "thedailywtf.com" is a spam site, so it won't let me submit)

  • JayC (unregistered) in reply to JayC
    JayC:
    C# does some blind execution path checking to see that all execution paths return a value. So not only is he following the "all case statements need a default" rule, in this case the C# compiler will insist on there being an unnecessary default statement or return statement after the case statement.
    Grr... I should mean to say
            public string bool2str(bool b)
            {
                switch (b)
                {
                    case true:
                        return System.Boolean.TrueString;
                    case false:
                        return System.Boolean.FalseString;
                } 
            }
    
    fails to compile. so either you switch "case false:" to "default:" (as mentioned) or you end up with some extraneous return statements or do some other modification.
  • (cs) in reply to Anonymous User
    Anonymous User:
    Is "bool" an object in C#? * No, it's a value type.

    Is "Bool" an object in C#?

    • Yes. In fact, I believe it's a 'Boxed' format of bool.

    The main difference between the two is how the data is stored; objects are generally 'like' C++ pointers (with a lot more guards) while value types are generally direct bits of memory. So values can't be 'null', while objects can. This also explains why a C# struct can't be null; it's considered a value-type, if a rather complex one.

    Also, Enums in C# are usually value-types (int by default, unless you override), so they shouldn't be nullable. So, to represent a base/unknown/default state that doesn't match a 'good' state, you would need either another value that you'd always have to check, or initial state of base/unknown/default to do the same thing.

    Bonus points: 'Enum' is its own class type with its own static functions that work nicely with enum types. Take a peek at it, see if any of them might be useful for what you're doing.

    Try again. ValueType derives from Object.

  • John Preston (unregistered) in reply to enim

    Yes... and no.

    It is an object - all value types inherit from object - but many things will not implicitly cast to Bool, like they would other types.

    Bool: http://msdn.microsoft.com/en-us/library/c8f5xwh7(v=VS.71).aspx

    Stupid Akismet won't let me post a link...

  • ell0bo (unregistered) in reply to Corey
    Corey:
    verto:
    I'm glad Alex reminded us of that previous article with FILE_NOT_FOUND. I had almost forgotten about it since yesterday.

    I think that was a preemptive FILE_NOT_FOUND. You know, to keep the "what about FILE_NOT_FOUND dumb-asses quiet."

    Technically, he could be catching a null type if C# allows you to do the same crazy evil Java (and PHP) do.

    dignissim... I miss the old digg

Leave a comment on “Truthful Strings”

Log In or post as a guest

Replying to comment #321225:

« Return to Article