Why does the C # compiler allow the return type and the variable type to be incorrect?

Consider the following code:

static void Main()
{
    dynamic a = 1;
    int b = OneMethod(a);
}

private static string OneMethod(int number)
{
    return "";
}

      

Note that type of b

and return type of OneMethod

do not match. However, it does throw and throw an exception at runtime. My question is, why did the compiler allow this? Or what is this philosophy?

The reason for this may be Compiler does not know which OneMethod would be called, because a is dynamic.

But why does he not see that there is only one OneMethod

. There will definitely be an exception at runtime.

+3


source to share


1 answer


Any expression that has an operand of type dynamic will be of the type of the dynamic itself.

This way your expression OneMethod(a)

returns an object that is dynamically typed

so the first part of your code is equivalent to

static void Main()
{
    dynamic a = 1;
    dynamic temp = OneMethod(a);
    int b = temp;
}

      



one way to argue why this is reasonable even in your case depends on whether you think the compiler should change the behavior for that particular line, depending on whether you add below method

private static T OneMethod<T>(T number)

      

Now the compiler will not know the type to be returned before execution. He doesn't even know which method is being called. General or not general. Wouldn't you be surprised if he flagged the assignment as a compilation error in the first case, and then by adding a completely different method, it was pushed to a runtime error?

+3


source







All Articles