Casting question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • AMP

    Casting question

    Hello,
    I have:
    ushort length= 4;
    ushort len;
    And I get an error here:
    length = len + 4;

    Error 6 Cannot implicitly convert type 'int' to 'ushort'. An explicit
    conversion exists (are you missing a cast?)

    Thanks Mike

  • Arne Vajhøj

    #2
    Re: Casting question

    AMP wrote:
    And I get an error here:
    length = len + 4;
    >
    Error 6 Cannot implicitly convert type 'int' to 'ushort'. An explicit
    conversion exists (are you missing a cast?)
    Try:

    length = (ushort)(len + 4);

    Arne

    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: Casting question

      AMP <ampeloso@gmail .comwrote:
      Hello,
      I have:
      ushort length= 4;
      ushort len;
      And I get an error here:
      length = len + 4;
      >
      Error 6 Cannot implicitly convert type 'int' to 'ushort'. An explicit
      conversion exists (are you missing a cast?)
      Basically, there's no operator which adds two ushorts together - they
      just get promoted to ints and then the addition is performed, resulting
      in an int.

      You'll need to cast the result, as Arne says.

      However, if you can use += instead, you don't need the extra cast:

      ushort x = 5;
      ushort y = 10;

      x += y;

      --
      Jon Skeet - <skeet@pobox.co m>
      http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
      If replying to the group, please do not mail me too

      Comment

      Working...