Search code examples
c#castingintshort

Why is not necessary a cast for this C# function?


Using C#; I just realized, declaring noValueNumber as const int and returning it from this short function.
Why there is not an error message, like:

Can't convert exxpression type int to return type short

    public static short ValueFromString(string onlyNumbersString)
    {
        if (onlyNumbersString.Length == 0)
        {
            const int noValueNumber = 999;

            return noValueNumber; // ¿...? 
        }

        return Int16.Parse(onlyNumbersString);
    }

Shouldn't be necessary a cast?, or there is, but hidden?


Solution

  • MSDN mentions that:

    You cannot implicitly convert nonliteral numeric types of larger storage size to short [...]

    A (constant) value that fits short though is OK with implicit conversion.

    Edit: Found the proper (positive) documentation for your example, Implicit Numeric Conversions Table (C# Reference), that states that:

    A constant expression of type int can be converted to sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant expression is within the range of the destination type.