Anomaly when using 'var' and 'dynamic'

前端 未结 2 849
北荒
北荒 2020-12-25 11:32

I\'ve run into a bit on an Anomaly where for the first time ever, using the var keyword bit me.

Take this very simple method

public stat         


        
2条回答
  •  囚心锁ツ
    2020-12-25 12:22

    1. Why does shouldBeNullableInt32 get implicitly typed as a dynamic when the return type of GetNullableInt32 clearly returns a Nullable?

    This is because while it is apparent to us that GetNullableInt32 is the method that is going to be called, because of dynamic binding, the actual method that does get called is deferred until run-time because it is being called with a dynamic parameter. There might be another overload of GetNullableInt32 that matches better the run-time value of thisIsAnInt32. That alternate method, which cannot be known until run-time, might return some other type than Int32?!

    As a result, the compiler, due to dynamic binding instead of static binding, cannot assume what the return type of the expression is at compile time and so the expression returns type dynamic. This can be seen by hovering over var.

    You appear to have already come to a satisfactory explanation for your second question here:

    • C# 4: Dynamic and Nullable<>

提交回复
热议问题