locked
Cannot implicitly convert type 'uint' to 'int'

    Question

  • I try to declar this statement:

    private static int[] MyArr = {0x243F6A88, 0x85A308D3, 0x13198A2E};

    And got this error

    Cannot implicitly convert type 'uint' to 'int'

    What wrong am I?

    Thank

    Tuesday, July 11, 2006 5:24 AM

Answers

  • If you're coming from a C++ background, C# is much more strict with types of literals.  0x85A308D3 is not considered an int because the top bit is high, forcing it to upcast to a uint so it will fit, despite legally representing a valid int value.  Use the unchecked keyword to avoid the error.  For example:

    private static int[] MyArr = {0x243F6A88, unchecked((int)0x85A308D3), 0x13198A2E};
     
    Tuesday, July 11, 2006 6:10 AM
    Moderator

All replies

  • Hexadecimal constant is interpreted as unsigned integer, you need to add casting:

    private static int[] MyArr = {(int)0x243F6A88, (int)0x85A308D3, (int)0x13198A2E};

    Tuesday, July 11, 2006 5:58 AM
  • If you're coming from a C++ background, C# is much more strict with types of literals.  0x85A308D3 is not considered an int because the top bit is high, forcing it to upcast to a uint so it will fit, despite legally representing a valid int value.  Use the unchecked keyword to avoid the error.  For example:

    private static int[] MyArr = {0x243F6A88, unchecked((int)0x85A308D3), 0x13198A2E};
     
    Tuesday, July 11, 2006 6:10 AM
    Moderator
  • Simply, the value you're attempting to assing to an int value exceed it's "range" capacity.

    Integral values expressed using hexadecimal notation are interpreted as UNSIGNED values.

    You can use an unchecked explicitly cast or choose a wider type, depending on your needs.

    Tuesday, July 11, 2006 8:03 AM
  •  Mr. BogoMips wrote:

    Integral values expressed using hexadecimal notation are interpreted as UNSIGNED values.

    Not necessarily. The type depends on the value you specify. The default type rules for numeric literals are the same whether you use decimal or hexadecimal representation.

    Tuesday, July 11, 2006 8:55 AM
  • Yes I'm agree... maybe my post was a bit confusing, I've already expressed the "range check rule" in the first period of my former post.
    Tuesday, July 11, 2006 8:59 AM
  • OK its work

    Thank you very much

    Tuesday, July 11, 2006 10:14 AM