Odd behavior change using a combination of var, dynamic and linq

I (lazily) used varin the source version of the code below and got a weird run-time exception in a completely different part of the code. Changing "var" to "int" fixed an exception at runtime, but I can't figure out why. I threw the code back to this example;

public class Program
{
    private static List<string> Test(string i) { return new List<string> {i}; }
    private static dynamic GetD() { return 1; }

    public static void Main()
    {
        int value1 = GetD();   // <-- int
        var result1 = Test("Value " + value1);
        // No problem, prints "Value 1", First() on List<string> works ok.
        Console.WriteLine(result1.First());

        var value2 = GetD();   // <-- var
        var result2 = Test("Value " + value2);
        // The below line gives RuntimeBinderException 
        // 'System.Collections.Generic.List<string>' does not contain a 
        // definition for 'First'
        Console.WriteLine(result2.First());
    }
}

I can see that the type "var" is dynamic, not int, but why does this type propagate and affect the behavior of the return value of the call on Test()?

EDIT: , ; , dynamic result2, , , IDE , List<string> Test(string) - , . , IDE , ?

+5
3

:

public static void Main()
{
    int value1 = GetD();   // <-- int
    List<string> result1 = Test("Value " + value1);
    // No problem, prints "Value 1", First() on List<string> works ok.
    Console.WriteLine(result1.First());

    dynamic value2 = GetD();   // <-- var
    dynamic result2 = Test("Value " + value2);
    // The below line gives RuntimeBinderException 
    // 'System.Collections.Generic.List<string>' does not contain a 
    // definition for 'First'
    Console.WriteLine(result2.First());
}

result2 - , ( ).

:

Console.WriteLine(Enumerable.First(result2));

UPDATE

IDE . :

private static List<int> Test(int i) { return new List<int> { i }; }

.

UPDATE2

7.6.5 #:

(Β§7.2.2), :

  • .
  • , - , .
+2

, First - , , .

:

+2

, iamge , .

GetType () Value

GetType() 2, , .

,

0

All Articles