Convert.ToInt32

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • 201211
    New Member
    • Jan 2012
    • 12

    Convert.ToInt32

    How to convert this code so don't get error: cannot implicitly convert type 'bool' to 'int'?

    int lans = SystemState.Con nectionsDesktop Count>0;

    This code SystemState.Con nectionsDesktop Count>0 is type boolean originally.

    I already try convert to this code:
    int lans = Convert.ToInt32 (SystemState.Co nnectionsDeskto pCount>0);

    and don't get any error but I think that it's not proper convert, any suggestion?
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    I'm confused... why are you storing the result of a boolean test in an integer? I'd imagine SystemState.Con nectionsDesktop Count is an integer, but as soon as you add the test, "> 0", the result becomes boolean. Are you actually looking for the count? That would make more sense, especially given your variable names. If so, just omit the "> 0" and lans will hold the count.

    If you're absolutely bent on converting a boolean to an integer, and to answer your question, it looks like there's no official conversion in .NET. You'll have to do it yourself, which means you'll have to decide what integer value is associated with false and which is associated with true. Traditionally (ie, in C/C++) there was no boolean type so it was just an integer, and false was 0 and true was 1.

    To that end, a simple if-then-else will do the trick and you can use the short-notation to save typing.

    Code:
    bool b1 = true;
    bool b2 = false;
    
    int i1 = (b1) ? 1 : 0;
    int i2 = (b2) ? 1 : 0;

    Comment

    • Subin Ninan
      New Member
      • Sep 2010
      • 91

      #3
      SystemState.Con nectionsDesktop Count already returns an integer value, so it is useless to call Convert.ToInt32 ()

      In case when return-type is not known, use TryParse() method.
      TryParse() returns bool value.

      Code:
      int desktopCount = 0;
      if(Int32.TryParse(SystemState.ConnectionsDesktopCount, out desktopCount))
      {
      //true
      }
      else
      {
      //false
      }

      Comment

      • 201211
        New Member
        • Jan 2012
        • 12

        #4
        because I use this code:
        void NetworkConnecti onChanged(objec t sender, Microsoft.Windo wsMobile.Status .ChangeEventArg s args)
        {
        lans = (int)args.NewVa lue;

        IsDocked = SystemState.Cra dlePresent || lans>0;

        }
        IsDocked is declare as boolean so I need to convert:

        int lans=System.Con vertToInt32(Sys temState.Connec tionsDesktopCou nt>0); to int.

        Comment

        Working...