Search code examples
c#dictionarydynamicvar

Why do I have to explicitly type a local variable?


In this example I had to explicitly declare the variable as IDictionary<string, string> instead of var but I don't understand why.

Can someone explain why when I originally declared it as var the Visual Studio tooltip indicated it was dynamic even though DictionaryHelper.ParseOptional() returns an IDictionary<string, string>?

ParseOptional is declared as:

public static IDictionary<string, string> ParseOptional(dynamic json, string variableName);

The mergeVariables parameter is coming from Json.Decode(), hence the dynamic variable.

I'm using Visual Studio 2019, .NET v4.7.2, C#7.3 in case it's relevant.

private static ICollection<IMergeVariable> ParseMergeVariables(dynamic mergeVariables)
{
    IDictionary<string, string> mergeDictionary = DictionaryHelper.ParseOptional(mergeVariables, "mergeVariables");

    return mergeDictionary?.Select(variable => new MergeVariable(variable.Key, variable.Value)).Cast<IMergeVariable>().ToList();
}

Solution

  • From Microsoft Docs:

    The result of most dynamic operations is itself dynamic.

    I believe this is because the types are resolved at runtime (hence "dynamic" typing).

    Related:

    Edit: I believe this case is covered by ECMA-334 C# Language Specification 5th Edition (December 2017), Section 12.7.6 Invocation expressions, subsection 12.7.6.1 General, which states that:

    An invocation-expression is dynamically bound (§12.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.