Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. Classic

Classic

Scheduled Pinned Locked Moved The Weird and The Wonderful
csharp
30 Posts 17 Posters 44 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • V Vasudevan Deepak Kumar

    Not with C# compiler right? The compiler 'barks' and strongly recommends an explicit casting. Isn't it?

    Vasudevan Deepak Kumar Personal Homepage Tech Gossips

    L Offline
    L Offline
    Luis Alonso Ramos
    wrote on last edited by
    #15

    Yep, in C# you can't compare a bool to 1 or an int to true without explicit casting.

    Luis Alonso Ramos Intelectix Chihuahua, Mexico

    My Blog!

    1 Reply Last reply
    0
    • L Lost User

      I ran some tests for speed for both cases and the results show that your assumption is correct. It seems compiler is smarter than I thought ;) So this case is closed and I learned something new to me and that is always a good thing :)

      W Offline
      W Offline
      wk633
      wrote on last edited by
      #16

      You ran a test for speed??? I put it in an app:

          bool IsNumberEven(int number)
          {
              return ((number % 2 == 0) ? true : false);
          }
          private void Form1\_Load(object sender, EventArgs e)
          {
      
              if (IsNumberEven(2))
              {
              }
      
              if (IsNumberEven(2) == true) { }
          }
      

      checked with ildasm, and they both turn into exactly the same IL code.

      // Code size 34 (0x22)
      .maxstack 2
      .locals init ([0] bool CS$4$0000)
      IL_0000: nop
      IL_0001: ldarg.0
      IL_0002: ldc.i4.2
      IL_0003: call instance bool csharpWindowsApp.Form1::IsNumberEven(int32)
      IL_0008: ldc.i4.0
      IL_0009: ceq
      IL_000b: stloc.0
      IL_000c: ldloc.0
      IL_000d: brtrue.s IL_0011
      IL_000f: nop
      IL_0010: nop
      IL_0011: ldarg.0
      IL_0012: ldc.i4.2
      IL_0013: call instance bool csharpWindowsApp.Form1::IsNumberEven(int32)
      IL_0018: ldc.i4.0
      IL_0019: ceq
      IL_001b: stloc.0
      IL_001c: ldloc.0
      IL_001d: brtrue.s IL_0021
      IL_001f: nop
      IL_0020: nop
      IL_0021: ret

      1 Reply Last reply
      0
      • D dighn

        Personally I don't find that to be horrible. It's completely correct and only slightly more redundant. It really makes no difference in practice. And no I'm not trying to defend my usage of it :) I don't lie :) :)

        J Offline
        J Offline
        John R Shaw
        wrote on last edited by
        #17

        Actually I do not know why that was even posted, there was absolutely nothing wrong with that code. Now if there was something in the “do something…” sections, that showed a problem – then it might have made since as a problem – otherwise it is great and legitimate code. Tinko101 – can just ignore my comment, because I have only been writing code for about 19 years or so, but I agree with you. ;)

        INTP "Program testing can be used to show the presence of bugs, but never to show their absence."Edsger Dijkstra

        T 1 Reply Last reply
        0
        • L Lost User

          I agree it's not horrible and that it can add to readability but it is still one comparison too many. It might get more obvious in different situation. Like (some stupid example): bool IsNumberEven(int number) {  return ((number % 2 == 0) ? true : false); } int Main() { int someNumber = 2^100; for (int i = 0; i < 100; i++) {  while (IsNumberEven(someNumber) == true)  {   someNumber /= 2;  } } } I think it is similar as using String object when one should use StringBuilder. It's OK for small number of iterations or single comparison, but can be time-consuming for large number of iterations.

          O Offline
          O Offline
          OR0N
          wrote on last edited by
          #18

          Testing if the number is even with modulus is the real horror .. :P

          L T 2 Replies Last reply
          0
          • O OR0N

            Testing if the number is even with modulus is the real horror .. :P

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #19

            Actually the real horror would be: bool IsEven(int someNumber) {  if (someNumber == 2 || someNumber == 4 || someNumber == 6 || // ok, you get the point)  {   return true;  }  else  {   return false;  } } :)

            O 1 Reply Last reply
            0
            • L Lost User

              Actually the real horror would be: bool IsEven(int someNumber) {  if (someNumber == 2 || someNumber == 4 || someNumber == 6 || // ok, you get the point)  {   return true;  }  else  {   return false;  } } :)

              O Offline
              O Offline
              OR0N
              wrote on last edited by
              #20

              A rumour has it that it always can be worse :)

              1 Reply Last reply
              0
              • J John R Shaw

                Actually I do not know why that was even posted, there was absolutely nothing wrong with that code. Now if there was something in the “do something…” sections, that showed a problem – then it might have made since as a problem – otherwise it is great and legitimate code. Tinko101 – can just ignore my comment, because I have only been writing code for about 19 years or so, but I agree with you. ;)

                INTP "Program testing can be used to show the presence of bugs, but never to show their absence."Edsger Dijkstra

                T Offline
                T Offline
                TClarke
                wrote on last edited by
                #21

                The only thing I can see wrong is that the boolean value isn't initialized. Now that is ban practice as in C/C++ values only get a default value in Debug mode. In Release mode it could be anything

                T 1 Reply Last reply
                0
                • T TClarke

                  The only thing I can see wrong is that the boolean value isn't initialized. Now that is ban practice as in C/C++ values only get a default value in Debug mode. In Release mode it could be anything

                  T Offline
                  T Offline
                  Tom Clement
                  wrote on last edited by
                  #22

                  I assumed the posted code was just missing an elipsis. Presumably there was something to set the Boolean value.

                  Tom Clement Serena Software, Inc. www.serena.com articles[^]

                  T 1 Reply Last reply
                  0
                  • T Tom Clement

                    I assumed the posted code was just missing an elipsis. Presumably there was something to set the Boolean value.

                    Tom Clement Serena Software, Inc. www.serena.com articles[^]

                    T Offline
                    T Offline
                    TClarke
                    wrote on last edited by
                    #23

                    Tell the compiler that ;)

                    1 Reply Last reply
                    0
                    • D dighn

                      Personally I don't find that to be horrible. It's completely correct and only slightly more redundant. It really makes no difference in practice. And no I'm not trying to defend my usage of it :) I don't lie :) :)

                      K Offline
                      K Offline
                      kenpanda
                      wrote on last edited by
                      #24

                      mmm...not sure !:mad: I already see worse ! You write a first test if (boolValue == true) during debugging, it appaers that you have to change the test if (boolValue != true) after a second debug you wish to change it again if (boolValue != false) As summary, do you think that this code is really readable, even the performance is the same... : **if (boolValue != !false)**:laugh:

                      1 Reply Last reply
                      0
                      • L Lost User

                        I'm sure you have all come across something like this. At least I see it way too often. So here it is in C# style: bool someBoolValue; if (someBoolValue == true) { // do something } else { // do something else }

                        D Offline
                        D Offline
                        dean wilde
                        wrote on last edited by
                        #25

                        I dont think theres anything wrong with that, the compiler is going to optimize it anyways, the reason I like it is because is simpler to read than the alternative and simpler is always better in code. The only argument you could make that one shouldnt do that is if you mistype and put if(someBoolValue=true) and do an assignment instead of a comparision. The workaround to that is to either put constants on the left hand side if(true==someBoolValue), which you should already be doing so the compiler catches other similar mistakes (like null checks), or set the compiler warning level to 4, which I would also recommend you do to let the compiler detect other bugs.

                        1 Reply Last reply
                        0
                        • T Tristan Rhodes

                          I occasionally find that slipping into my code. Looking back over it a few minutes later reveals my brain fart. :)

                          ------------------------------- Carrier Bags - 21st Century Tumbleweed.

                          D Offline
                          D Offline
                          dojohansen
                          wrote on last edited by
                          #26

                          That, and the classic ternary (sMethod == "read"? true : false) What I never understood is why these people stop so soon. The concept is readily extended... if (doIt) => if (doIt == true) => if ((doIt == true) == true) ... and combined bool flag = ((doIt == true) == true? true : false); if (flag != false) doIt = true; We could go on all night...

                          1 Reply Last reply
                          0
                          • D dighn

                            Personally I don't find that to be horrible. It's completely correct and only slightly more redundant. It really makes no difference in practice. And no I'm not trying to defend my usage of it :) I don't lie :) :)

                            D Offline
                            D Offline
                            dojohansen
                            wrote on last edited by
                            #27

                            It makes no difference, just like if (((true == myFlagVariable) == true) != false) is in fact equivalent to if (myFlagVariable) It's just that one version shows that the programmer understands that a boolean variable is in fact a boolean expression. So while it doesn't do much damage, it does show a lack of understanding -- excepting the occasional brainfart, which can surely happen to anyone. I've also noted the habit of C programmers to write if (null == var) ... which to me just doesn't read naturally! I realise that they do this to avoid an unintensional assignment - a common and often subtle bug in C code: if (var = null) ... But in C# an assignment statement is not legal in an if condition, so it is a pointless practice. But I won't deny that habits are powerful and it may not be so easy for an old dog (C programmer) to change his ways. (I wish it was "her" ways more often, but for some reason girls are few and far between in our community.)

                            D 1 Reply Last reply
                            0
                            • D dojohansen

                              It makes no difference, just like if (((true == myFlagVariable) == true) != false) is in fact equivalent to if (myFlagVariable) It's just that one version shows that the programmer understands that a boolean variable is in fact a boolean expression. So while it doesn't do much damage, it does show a lack of understanding -- excepting the occasional brainfart, which can surely happen to anyone. I've also noted the habit of C programmers to write if (null == var) ... which to me just doesn't read naturally! I realise that they do this to avoid an unintensional assignment - a common and often subtle bug in C code: if (var = null) ... But in C# an assignment statement is not legal in an if condition, so it is a pointless practice. But I won't deny that habits are powerful and it may not be so easy for an old dog (C programmer) to change his ways. (I wish it was "her" ways more often, but for some reason girls are few and far between in our community.)

                              D Offline
                              D Offline
                              dojohansen
                              wrote on last edited by
                              #28

                              I'll rush to correct myself... "an assignment statement is not legal in an if condition" isn't strictly true. What is true is that an if condition in C# requires a boolean expression. For the present purpose it doesn't greatly matter, since the accidental assignment cannot happen in C#, but in general, an assignment can indeed be part of the boolean expression, even if there is little reason to make our code harder to read in this way. if ((list.Capacity = count) > 1024) { ... } This is perfectly legal, but not as readable as list.Capacity = count; if (count > 1024) { ... } which is equivalent (i.e. both versions produce the same IL code).

                              1 Reply Last reply
                              0
                              • A Andy Brummer

                                While I don't write boolValue == true, I do write boolValue == false since it stands out more then !boolValue.


                                I can imagine the sinking feeling one would have after ordering my book, only to find a laughably ridiculous theory with demented logic once the book arrives - Mark McCutcheon

                                D Offline
                                D Offline
                                dojohansen
                                wrote on last edited by
                                #29

                                It stands out more?? How clear do you need it to be? IMO, (b == true) "stands out" more than (b), so if this was a guiding principle we ought to write it all the time. Perhaps we should also write int i, count, n; ... i = i.Add(count.Multiply(n)); instead of i += count * n; Admittedly the last example is a stretch. And the issue is surely quite academical - there are a few other bad coding habits I can think of, and methodology (or lack thereof), and much else, that matters rather a lot more in the end. But for the sake of academic nitpicking (which I think is rather fun) I'd still say "less is usually better". The only exception is when less code makes something obscure or unreadable. In my judgement (!b) clearly does NOT qualify; it is as clear as it can be.

                                1 Reply Last reply
                                0
                                • O OR0N

                                  Testing if the number is even with modulus is the real horror .. :P

                                  T Offline
                                  T Offline
                                  Tom Clement
                                  wrote on last edited by
                                  #30

                                  This might be even better. After all, it's the way I do it in my head. :laugh:

                                  bool IsNumberEven(int number) {
                                  string sNumber = number.ToString();
                                  string sLastDigit = sNumber[sNumber.Length - 1];
                                  if(sLastDigit == '0' || sLastDigit == '2' || sLastDigit == '4' || sLastDigit == '6' || sLastDigit == '8' ) {
                                  return true;
                                  }
                                  else {
                                  return false;
                                  }
                                  }

                                  Tom Clement articles[^]

                                  1 Reply Last reply
                                  0
                                  Reply
                                  • Reply as topic
                                  Log in to reply
                                  • Oldest to Newest
                                  • Newest to Oldest
                                  • Most Votes


                                  • Login

                                  • Don't have an account? Register

                                  • Login or register to search.
                                  • First post
                                    Last post
                                  0
                                  • Categories
                                  • Recent
                                  • Tags
                                  • Popular
                                  • World
                                  • Users
                                  • Groups