Below is the exact code I am running. Why does the compiler return dynamic and not type MyClass?
My project is running on .NET Framework 4.7.2, but I configured it to use latest C# by adding public static class IsExternalInit { } and
<PropertyGroup>
<LangVersion>latest</LangVersion>
</PropertyGroup>
My code:
internal class Program
{
class MyClass
{
}
static class MyParser
{
public static MyClass Parse(dynamic data)
{
return new MyClass();
}
}
static void Do(dynamic data)
{
var parsedObj = MyParser.Parse(data);
...
}
static void Main(string[] args)
{
Do(JsonConvert.DeserializeObject(""));
}
}

Why does compiler return
dynamicwhen it should return a specific type?
The question presupposes a falsehood. The compiler's behaviour is correct, so asking why it should do an incorrect thing makes it hard to answer your question.
Instead I'll answer the question "what section of the specification determines when the compiler should classify an invocation as dynamic?"
I refer you to section 11.7.8.1 of the specification, which states:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#11781-general
An invocation_expression is dynamically bound (§11.3.3) if at least one of the following holds:
- The primary_expression has compile-time type dynamic.
- At least one argument of the optional argument_list has compile-time type dynamic.
In this case, the compiler classifies the invocation_expression as a value of type dynamic.
data is "at least one argument" that has type dynamic, so there you go.
In your specific case, the section on additional error checks applies -- but this section does not affect the classification of the invocation's type.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#1165-compile-time-checking-of-dynamic-member-invocation
If your "why" question was not answered by a reference to the specification, then I'd encourage you to reformulate it as a "what" question. It's hard to know when a "why" question has been answered satisfactorily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With