Use the dynamic keyword/.NET 4.6 feature in Unity

The first step is to check if Unity recognizes these 2 basic C# 6 features from MS site.

1.Try "Index Initializers" feature:

private Dictionary<int, string> webErrors = new Dictionary<int, string>
{
    [404] = "Page not Found",
    [302] = "Page moved, but left a forwarding address.",
    [500] = "The web server can't come out to play today."
};

2. then "String Interpolation" feature:

private string FirstName = "";
private string LastName = "";
public string FullName => $"{FirstName} {LastName}";

If they give you error then the problem is not just the dynamic keyword but a problem that Visual Studio cannot recognize the .NET version being set by Unity.

From the comment section your Unity failed to compile the first example.


Go through the steps one by one for a possible fix. Do not skip of them.

1.Go to Edit --> Project Settings --> Player --> Other Settings --> Configuration --> Scripting Runtime Version --> Experimental (.Net 4.6 Equivalent).

2.Go to Edit --> Project Settings --> Player --> Other Settings --> Configuration --> Api Compatibility Level --> .NET 4.6

3.Restart Unity Editor and Visual Studio. You must restart both.

Test both C# features above. If they work then the dynamic keyword should as-well. If they don't then move on to #4.

4.Update Visual Studio. This is very important. Update the visual Studio to the latest version/patch.

5.If you can't still get both C#6 features above to compile then Re-install both Visual Studio and Unity then perform step #1 and #2 again as some files are missing.

6.Finally, if you get both C#6 features working but the dynamic keyword is still not working then update from Unity 2017.1 to Unity 2017.2. This version fixed many .NET issues.

Note that I am using Unity 2017.2 with the dynamic keyword without any issue. Also, GraphQL is working fine.


I seem to have found a solution

Navigate to Edit > Project Settings > Player > Other Settings > Configuration > API Compatibility Level and change from .NET Standard 2.0 to .NET 4.x

This immediately removed the compiler error and allowed me to run code using the dynamic keyword.

Let me know if that was useful