• Visitors can check out the Forum FAQ by clicking this link. You have to register before you can post: click the REGISTER link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below. View our Forum Privacy Policy.
  • Want to receive the latest contracting news and advice straight to your inbox? Sign up to the ContractorUK newsletter here. Every sign up will also be entered into a draw to WIN £100 Amazon vouchers!

C# test - no googling

Collapse
X
  •  
  • Filter
  • Time
  • Show
Clear All
new posts

    C# test - no googling

    Why does the following not compile?

    Code:
    short x = 2, y = 3;
    short z = x + y; // Compile-time error

    #2
    Does it try and assign x and y both as integers, without casting them to a short thus throwing an exception ?
    Doing the needful since 1827

    Comment


      #3
      No class/function definitions...

      Comment


        #4
        Can I ask Bob?

        Comment


          #5
          Originally posted by amcdonald View Post
          Does it try and assign x and y both as integers, without casting them to a short thus throwing an exception ?
          Why does it try and assign them as integers?

          Comment


            #6
            Originally posted by BrilloPad View Post
            Can I ask Bob?
            He's asking ATW.

            Comment


              #7
              y ends up an integer not a short.

              Then the implicit conversion fails as you can't implicitly convert to a short.
              merely at clientco for the entertainment

              Comment


                #8
                Originally posted by DimPrawn View Post
                Why does the following not compile?

                Code:
                short x = 2, y = 3;
                short z = x + y; // Compile-time error
                Maybe the compiler infers the type of "x + y" to be an int since it could overflow a short. Then youd have to cast that explicitly to a short to assign to "z".

                Comment


                  #9
                  Originally posted by DimPrawn View Post
                  Why does it try and assign them as integers?
                  Can't remember why, when the shorts were declared I assume it implicitly converts them from integers to shorts, but when you try and add the x and y it tries to pass a reference to x and y as integers ?
                  Doing the needful since 1827

                  Comment


                    #10
                    You are close.

                    Yes the compiler assigns the number as integers, because there is no + operator on a short! Then of course the implicit conversion of an int to a short fails at compile time.

                    Comment

                    Working...
                    X