Dynamic parameter causes compiler to think method return is dynamic
Asked Answered
D

1

36

If I have a dynamic parameter the compiler seems to ditch the return type and think it's dynamic.

For example:

public MethodResult IsValid(object userLogin)
{     
  return new MethodResult();
}

You would think that:

var isValidResult = IsValid(someObject());

Should read as

dynamic -> MethodResult 

But it thinks that it is:

dynamic -> dynamic

Does adding a dynamic parameter to the signature completely stop the compiler from knowing what the return should be despite the return being strongly typed?

Deluna answered 19/10, 2011 at 23:39 Comment(0)
P
33

Yes, dynamic stops the compiler from knowing the type on any parameters, properties, or method return types. Add an explicit cast like:

(MethodResult)IsValid(someObject));

The reason here is that once you enter the dynamic world in C# you are going into late binding. The compiler can't verify this code because it can no longer use any static type analysis. So it defers until later. You can help overcome this by providing static casts as a guide for the compiler.

Peepul answered 19/10, 2011 at 23:49 Comment(1)
For more details check MSDN - Using dynamic types - "Overload resolution occurs at run time instead of at compile time if one or more of the arguments in a method call have the type dynamic, or if the receiver of the method call is of type dynamic." - so as result it is not known till runtime what method will be called at all.Thousandfold

© 2022 - 2024 — McMap. All rights reserved.