Shin
Shin

Reputation: 673

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?

Upvotes: 0

Views: 100

Answers (4)

Oskar Lindberg
Oskar Lindberg

Reputation: 2294

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.

Upvotes: 3

Konrad Kokosa
Konrad Kokosa

Reputation: 16898

This is because compiler is wise enough to see that 999 is proper short value and it is const so it will not be changed (the usage of noValueNumber can be replaced in fact by this value simply). If you will try for example to return 40000 you will get an compilation error:

Constant value '40000' cannot be converted to a 'short'

In other way, if you remove const you will get expected:

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

In yet other words, if you decompile your orignal function, you get:

public static short ValueFromString(string onlyNumbersString)
{
    short result;
    if (onlyNumbersString.Length == 0)
    {
        result = 999;
    }
    else
    {
        result = short.Parse(onlyNumbersString);
    }
    return result;
}

This is how compiler "sees" this code, and as you see, there is no const int here at all.

Upvotes: 1

Grx70
Grx70

Reputation: 10349

999 is a valid short number. Since you use const int noValueNumber (const being the key here), the name noValueNumber is used as an alias for 999. During pre-compile processing, each occurrence of noValueNumber is replaced with 999, so the compiled code is actually return 999;.

Upvotes: 0

walther
walther

Reputation: 13600

I'd say it's because you've defined the variable as a constant with a value 999 (which is a valid Int16 value), so it can easily work with that. If you'd remove const from the definition, it would stop working. Smart compiler :)

Upvotes: 0

Related Questions