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. General Programming
  3. C#
  4. Cannot implicitly convert type 'object' to 'bool'

Cannot implicitly convert type 'object' to 'bool'

Scheduled Pinned Locked Moved C#
helpquestion
42 Posts 17 Posters 1 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.
  • O Orjan Westin

    There's a difference between

    if (btnPause.Content = "Pause")

    and

    if (btnPause.Content == "Pause")

    You aren't comparing with btnPause.Content, but assigning to it. The assignment operator returns the assigned object, so in effect your code is like this:

    btnPause.Content = "Pause";
    if (btnPause)

    It's a classic typo-bug, and the safest way of avoiding it is to make a habit of putting the constant (if you have one) to the left:

    if ("Pause" = btnPause.Content)

    This would give a compiler error along the lines of "Cannot assign to constant", which is more helpful.

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

    I already suggested this above; you may want to read Harold, Luc and Keith's comments in response. Also note that someone around here really hates this idea and is downvoting us for suggesting it. I've given you a 5 to compensate. ;)

    It's time for a new signature.

    O 1 Reply Last reply
    0
    • L Lost User

      I already suggested this above; you may want to read Harold, Luc and Keith's comments in response. Also note that someone around here really hates this idea and is downvoting us for suggesting it. I've given you a 5 to compensate. ;)

      It's time for a new signature.

      O Offline
      O Offline
      Orjan Westin
      wrote on last edited by
      #12

      Yes, I saw that once I'd replied. It was the changed subject line that threw me off. Sorry, I'm new in the neighbourhood. :)

      L E 2 Replies Last reply
      0
      • L Lost User

        Instead of coding:

        if (btnPause.Content == "Pause")

        try writing it this way round

        if ("Pause" == btnPause.Content)

        then when you inadvertently miss one of the = signs the compiler will give you a much more useful message.

        It's time for a new signature.

        P Offline
        P Offline
        PIEBALDconsult
        wrote on last edited by
        #13

        I used to work in a shop (doing just plain C) that had that specified in the coding standards. It made no sense to me, but I went along. One day I was talking with "the guru" (who probably wrote the standard) and he agreed that it was pointless so he didn't enforce it. The basic problem is that it only works when comparing an Lvalue and an Rvalue; many times that is not the case, so you need to think about what you are doing and recognize the situation. And if you can do that, then chances are you won't make that mistake anyway. When it comes right down to it; anyone who is prone to that kind of mistake is also unlikely to remember the rule. By the way... HP C V7.3-009 on OpenVMS Alpha V8.3 says:

        JB> cc aa.c /warn=(enable=(check),verbose)

        if ( result = 5 )
        

        ....^
        %CC-I-CONTROLASSIGN, In this statement, the assignment expression "result=5" is used as the controlling expression of an if, while o
        r for statement.
        at line number 13 in file MY$ROOT:[000000]AA.C;3
        Description: A common user mistake is to accidentally use assignment operator "=" instead of the equality operator "==" in an expres
        sion that controls a transfer. For example saying if (a = b) instead of if (a == b). While using the assignment operator is valid,
        it is often not what was intended. When this message is enabled, the compiler will detect these cases at compile-time. This can oft
        en avoid long debugging sessions needed to find the bug in the user's program.
        User Action: Make sure that the assignment operator is what is expected.

        if ( 5 = result )
        

        .........^
        %CC-E-NEEDLVALUE, In this statement, "5" is not an lvalue, but occurs in a context that requires one.
        at line number 18 in file MY$ROOT:[000000]AA.C;3
        Description: An expression that must be an lvalue was not an lvalue. For example, the operand of the address-of operator must be an
        lvalue.
        User Action: Modify the expression so that it is an lvalue.

        Edit:

        C:\>cc aa
        Borland C++ 5.5 for Win32 Copyright (c) 1993, 2000 Borland
        aa.c:
        Warning W8060 aa.c 14: Possibly incorrect assignment in function main

        C:\>\mingw\bin\gcc -Wall aa.c
        aa.c: In function `main':
        aa.c:14: warning: suggest parentheses around assignment used as truth value

        modified on Saturday, August 7, 2010 11:40 PM

        L L 2 Replies Last reply
        0
        • P PIEBALDconsult

          I used to work in a shop (doing just plain C) that had that specified in the coding standards. It made no sense to me, but I went along. One day I was talking with "the guru" (who probably wrote the standard) and he agreed that it was pointless so he didn't enforce it. The basic problem is that it only works when comparing an Lvalue and an Rvalue; many times that is not the case, so you need to think about what you are doing and recognize the situation. And if you can do that, then chances are you won't make that mistake anyway. When it comes right down to it; anyone who is prone to that kind of mistake is also unlikely to remember the rule. By the way... HP C V7.3-009 on OpenVMS Alpha V8.3 says:

          JB> cc aa.c /warn=(enable=(check),verbose)

          if ( result = 5 )
          

          ....^
          %CC-I-CONTROLASSIGN, In this statement, the assignment expression "result=5" is used as the controlling expression of an if, while o
          r for statement.
          at line number 13 in file MY$ROOT:[000000]AA.C;3
          Description: A common user mistake is to accidentally use assignment operator "=" instead of the equality operator "==" in an expres
          sion that controls a transfer. For example saying if (a = b) instead of if (a == b). While using the assignment operator is valid,
          it is often not what was intended. When this message is enabled, the compiler will detect these cases at compile-time. This can oft
          en avoid long debugging sessions needed to find the bug in the user's program.
          User Action: Make sure that the assignment operator is what is expected.

          if ( 5 = result )
          

          .........^
          %CC-E-NEEDLVALUE, In this statement, "5" is not an lvalue, but occurs in a context that requires one.
          at line number 18 in file MY$ROOT:[000000]AA.C;3
          Description: An expression that must be an lvalue was not an lvalue. For example, the operand of the address-of operator must be an
          lvalue.
          User Action: Modify the expression so that it is an lvalue.

          Edit:

          C:\>cc aa
          Borland C++ 5.5 for Win32 Copyright (c) 1993, 2000 Borland
          aa.c:
          Warning W8060 aa.c 14: Possibly incorrect assignment in function main

          C:\>\mingw\bin\gcc -Wall aa.c
          aa.c: In function `main':
          aa.c:14: warning: suggest parentheses around assignment used as truth value

          modified on Saturday, August 7, 2010 11:40 PM

          L Offline
          L Offline
          Luc Pattyn
          wrote on last edited by
          #14

          Right. I've seen some C compilers (don't recall which, I've used so many for all kinds of embedded systems) also warning about the probably mistaken assignment in an if statement. :)

          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

          Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

          1 Reply Last reply
          0
          • T Tichaona J

            I keep getting the below error message when I try and run my code. Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) When I try run the below code: private void Pause_Click(object sender, RoutedEventArgs e) { if (btnPause.Content = "Pause") <<<<

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #15

            Personally, I'd prefer to hide the Pause button and show the resume button rather than repurpose the one button and do string compares.

            1 Reply Last reply
            0
            • O Orjan Westin

              Yes, I saw that once I'd replied. It was the changed subject line that threw me off. Sorry, I'm new in the neighbourhood. :)

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

              Cool Cow Orjan wrote:

              Sorry, I'm new in the neighbourhood.

              No problem, we all make mistakes from time to time. And welcome to CodeProject, judging by some of your posts I have seen I am sure your contributions will have a positive impact for many people. :thumbsup:

              It's time for a new signature.

              1 Reply Last reply
              0
              • P PIEBALDconsult

                I used to work in a shop (doing just plain C) that had that specified in the coding standards. It made no sense to me, but I went along. One day I was talking with "the guru" (who probably wrote the standard) and he agreed that it was pointless so he didn't enforce it. The basic problem is that it only works when comparing an Lvalue and an Rvalue; many times that is not the case, so you need to think about what you are doing and recognize the situation. And if you can do that, then chances are you won't make that mistake anyway. When it comes right down to it; anyone who is prone to that kind of mistake is also unlikely to remember the rule. By the way... HP C V7.3-009 on OpenVMS Alpha V8.3 says:

                JB> cc aa.c /warn=(enable=(check),verbose)

                if ( result = 5 )
                

                ....^
                %CC-I-CONTROLASSIGN, In this statement, the assignment expression "result=5" is used as the controlling expression of an if, while o
                r for statement.
                at line number 13 in file MY$ROOT:[000000]AA.C;3
                Description: A common user mistake is to accidentally use assignment operator "=" instead of the equality operator "==" in an expres
                sion that controls a transfer. For example saying if (a = b) instead of if (a == b). While using the assignment operator is valid,
                it is often not what was intended. When this message is enabled, the compiler will detect these cases at compile-time. This can oft
                en avoid long debugging sessions needed to find the bug in the user's program.
                User Action: Make sure that the assignment operator is what is expected.

                if ( 5 = result )
                

                .........^
                %CC-E-NEEDLVALUE, In this statement, "5" is not an lvalue, but occurs in a context that requires one.
                at line number 18 in file MY$ROOT:[000000]AA.C;3
                Description: An expression that must be an lvalue was not an lvalue. For example, the operand of the address-of operator must be an
                lvalue.
                User Action: Modify the expression so that it is an lvalue.

                Edit:

                C:\>cc aa
                Borland C++ 5.5 for Win32 Copyright (c) 1993, 2000 Borland
                aa.c:
                Warning W8060 aa.c 14: Possibly incorrect assignment in function main

                C:\>\mingw\bin\gcc -Wall aa.c
                aa.c: In function `main':
                aa.c:14: warning: suggest parentheses around assignment used as truth value

                modified on Saturday, August 7, 2010 11:40 PM

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

                I thought I had seen something like that in my days as a UNIX programmmer, it must have been gcc and possibly Sun' own C/C++ compiler.

                It's time for a new signature.

                1 Reply Last reply
                0
                • T Tichaona J

                  I keep getting the below error message when I try and run my code. Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) When I try run the below code: private void Pause_Click(object sender, RoutedEventArgs e) { if (btnPause.Content = "Pause") <<<<

                  C Offline
                  C Offline
                  cor2879
                  wrote on last edited by
                  #18

                  Personally when performing value comparisons with strings (and many other types) I find I am far less prone to syntax errors if I make myself use the "Equals" method. With strings in particular, it is a good practice to use the static method

                  String.Equals(string a, string b)

                  as this eliminates the possibility of a null reference exception. With this in mind, the boolean in your if statement would look like this:

                  if (String.Equals(btnPause.Content, "Pause"))

                  "We are men of action; lies do not become us."

                  J 1 Reply Last reply
                  0
                  • T Tichaona J

                    I keep getting the below error message when I try and run my code. Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) When I try run the below code: private void Pause_Click(object sender, RoutedEventArgs e) { if (btnPause.Content = "Pause") <<<<

                    M Offline
                    M Offline
                    michaelbierly
                    wrote on last edited by
                    #19

                    you are trying to assign "Pause" to btnPause.content (=) you need the equality comparison operator (==) I dont have a lot of context to what you are doing, but you might want to try refering to sender rather than btnPause in the code.

                    1 Reply Last reply
                    0
                    • T Tichaona J

                      I keep getting the below error message when I try and run my code. Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) When I try run the below code: private void Pause_Click(object sender, RoutedEventArgs e) { if (btnPause.Content = "Pause") <<<<

                      T Offline
                      T Offline
                      tom1443
                      wrote on last edited by
                      #20

                      Ah, bitten by the old "==" typo. Don't feel bad it was my first coding mistake in C 25 years ago. I still occasionally make that error but it usually takes me a whole lot less time to find it.

                      1 Reply Last reply
                      0
                      • T Tichaona J

                        I keep getting the below error message when I try and run my code. Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) When I try run the below code: private void Pause_Click(object sender, RoutedEventArgs e) { if (btnPause.Content = "Pause") <<<<

                        D Offline
                        D Offline
                        Devi Ganesan
                        wrote on last edited by
                        #21

                        error in line "if (btnPause.Content = "Pause") " it should be like btnpauser.content == "Pause" hopefully this should fix the error

                        1 Reply Last reply
                        0
                        • L Luc Pattyn

                          it really should say

                          if() expects a boolean and "btnPause.Content" isn't a boolean nor convertible to one

                          and it could add

                          there is an assignment in your expression; did you intend to test for equality? if so use ==

                          Why can't error messages be very specific, after all the parser is specific when it checks things.

                          harold aptroot wrote:

                          I did not vote "bad answer"

                          Neither did I, although I didn't like it much; the user should not change his habits just because the compiler lacks proper error reporting. The suggestion may be OK for C/C++, but doesn't help much for C# code. :)

                          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                          Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                          modified on Saturday, August 7, 2010 10:51 AM

                          T Offline
                          T Offline
                          TNCaver
                          wrote on last edited by
                          #22

                          Here's a radical idea: why not throw out the '==' and '===' confusion and make the compiler use the single '=' as either an assignment or a comparative operator depending on the context, like VB does? Oh yeah, because we don't want C# to be like VB with all the stigma associated with such simpleton languages. Sorry, I forgot.

                          L K J 3 Replies Last reply
                          0
                          • T TNCaver

                            Here's a radical idea: why not throw out the '==' and '===' confusion and make the compiler use the single '=' as either an assignment or a comparative operator depending on the context, like VB does? Oh yeah, because we don't want C# to be like VB with all the stigma associated with such simpleton languages. Sorry, I forgot.

                            L Offline
                            L Offline
                            Luc Pattyn
                            wrote on last edited by
                            #23

                            I don't care much what symbol(s) get used for operators, I started out in Fortran which used .EQ. for equality testing. However if assignment and equality test operators coincide, some semantics get lost, as in a=b==c versus a=b=c; there is only so much context analysis can do. :)

                            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                            Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                            1 Reply Last reply
                            0
                            • T Tichaona J

                              I keep getting the below error message when I try and run my code. Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) When I try run the below code: private void Pause_Click(object sender, RoutedEventArgs e) { if (btnPause.Content = "Pause") <<<<

                              B Offline
                              B Offline
                              Bob1000
                              wrote on last edited by
                              #24

                              Silly mistake, but hey CodeProject a bit of downer to place this question on the daily news email. or maybe someone is having a bad day and wants to pass it on.....:)

                              1 Reply Last reply
                              0
                              • O Orjan Westin

                                Yes, I saw that once I'd replied. It was the changed subject line that threw me off. Sorry, I'm new in the neighbourhood. :)

                                E Offline
                                E Offline
                                ErrolErrol
                                wrote on last edited by
                                #25

                                Ok, first things first...If this is August 10th, I will gladly eat this post. Why are the messages all dated the 10th? Secondly, being "new in the neighbourhood" sounds like a good reason for everyone to pile on and really "get you" for not plowing through all of the messages!! LOL! :laugh:

                                O 1 Reply Last reply
                                0
                                • T TNCaver

                                  Here's a radical idea: why not throw out the '==' and '===' confusion and make the compiler use the single '=' as either an assignment or a comparative operator depending on the context, like VB does? Oh yeah, because we don't want C# to be like VB with all the stigma associated with such simpleton languages. Sorry, I forgot.

                                  K Offline
                                  K Offline
                                  Kenneth Kasajian
                                  wrote on last edited by
                                  #26

                                  You joke, but there's a lot of truth to that. you need the braces { and the weird 'for' syntax, the ++/-- operators and == for equality. it means it's a real programming language. Microsoft could have solved all of the technical problems without C#, by simply releasing .NET with only VB as the language, and it would simply have been the new version of VB, and the rest of us would be dealing with CString and MFC message maps. But now we get to implement IDispoable!

                                  ken@kasajian.com / www.kasajian.com

                                  1 Reply Last reply
                                  0
                                  • L Lost User

                                    :(( suitably chastised ...

                                    It's time for a new signature.

                                    A Offline
                                    A Offline
                                    alton turner
                                    wrote on last edited by
                                    #27

                                    I thought it was a good idea, though I could never do that myself.

                                    1 Reply Last reply
                                    0
                                    • L Lost User

                                      Instead of coding:

                                      if (btnPause.Content == "Pause")

                                      try writing it this way round

                                      if ("Pause" == btnPause.Content)

                                      then when you inadvertently miss one of the = signs the compiler will give you a much more useful message.

                                      It's time for a new signature.

                                      J Offline
                                      J Offline
                                      Jonathan C Dickinson
                                      wrote on last edited by
                                      #28

                                      Yeugh! That looks too much like C++ for my liking. The alternate compiler error is just as confusing; and the alternate code is more confusing to read. The reason they did things the second way in C++ is because:

                                      if (btnPause->Content = "Pause") // Compiles with no errors or warnings NPNPNP

                                      And:

                                      if ("Pause" = btnPause->Content) // Doesn't compile (error)

                                      We don't need to resort to such language hacks in C#. Please, for the kittens!

                                      He who asks a question is a fool for five minutes. He who does not ask a question remains a fool forever. [Chineese Proverb] Jonathan C Dickinson (C# Software Engineer)

                                      1 Reply Last reply
                                      0
                                      • T TNCaver

                                        Here's a radical idea: why not throw out the '==' and '===' confusion and make the compiler use the single '=' as either an assignment or a comparative operator depending on the context, like VB does? Oh yeah, because we don't want C# to be like VB with all the stigma associated with such simpleton languages. Sorry, I forgot.

                                        J Offline
                                        J Offline
                                        Jonathan C Dickinson
                                        wrote on last edited by
                                        #29

                                        Nope. Firstly, there is no === in C#. Secondly the 'inconvenience' of == is outweighed by its benefit. For example:

                                        while((line = reader.ReadLine()) != null)

                                        This would be more difficult to read (albeit probably less confusing) without the explicit identity equality operator:

                                        line = reader.ReadLine();
                                        while(line != null)
                                        {

                                        line = reader.ReadLine();
                                        }

                                        The second block has absolutely no intent locality (keeping the same ideas in the same place in code).

                                        He who asks a question is a fool for five minutes. He who does not ask a question remains a fool forever. [Chineese Proverb] Jonathan C Dickinson (C# Software Engineer)

                                        L 1 Reply Last reply
                                        0
                                        • C cor2879

                                          Personally when performing value comparisons with strings (and many other types) I find I am far less prone to syntax errors if I make myself use the "Equals" method. With strings in particular, it is a good practice to use the static method

                                          String.Equals(string a, string b)

                                          as this eliminates the possibility of a null reference exception. With this in mind, the boolean in your if statement would look like this:

                                          if (String.Equals(btnPause.Content, "Pause"))

                                          "We are men of action; lies do not become us."

                                          J Offline
                                          J Offline
                                          Jonathan C Dickinson
                                          wrote on last edited by
                                          #30

                                          You can't get a NRE using the == operator. The .Net runtime essentially does this:

                                           if (Object.ReferenceEquals(a, null) && Object.ReferenceEquals(b, null)) return true;
                                          

                                          else if (Object.ReferenceEquals(a, null) || Object.ReferenceEquals(b, null)) return false;
                                          else return a.Equals(b);

                                          Unless you override the == operator (in which case you should do this in the header). The String.Equals is better because you would be more inclined to use the StringComparison enum[^] - but that is only the case for Strings.

                                          He who asks a question is a fool for five minutes. He who does not ask a question remains a fool forever. [Chineese Proverb] Jonathan C Dickinson (C# Software Engineer)

                                          C 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