urig urig -4 years ago 50
C# Question

Why does Visual Studio think my "yield return" method returns a dynamic object?

I've written a method that returns an

IEnumerable<T>
using
yield return
like so:

public IEnumerable<Row> ConvertExcelToRows(IExcelDataReader reader)
{
while (reader.Read())
{
var row = new Row();
// do some work. No dynamic objects here whatsoever
yield return row;
}
}


When I consume my method and follow it with LINQ extension methods, Visual Studio shows the return value to be of type
dynamic
:

enter image description here

The type of
rows
in the screen shot above is
dynamic
when it should be
List<Row>
.

Why is this happening and how can I fix it?

Details:
-
Row
is just a class I wrote up. All primitive properties, no dynamic ones.

UPDATE: The horror! Even if I explicitly call
.ToList<Row>()
I still get a dynamic object.

KEY UPDATE: In the process of improving the screenshot above, I've changed the declaration of
excelReader
from
var
to
IExcelDataReader
. This solved my problem.

When I changed back to
var
, I saw that the inferred type of
excelReader
is indeed the contagious
dynamic
.

Would still love an explanation of why a dynamic input argument to my method would "infect" the type of the output.

Answer Source

dynamic operates by a contagion principle. If anything coming into an expression is dynamic, then the compiler can make no guarantees at compile time about what might come out -- so what comes out is considered dynamic as well.

Something upstream, a parameter to a method, the object you called the method on, or a term in an expression, is dynamic. You need to find out what. An obvious candidate is excelReader: Where did it come from, and where did that object come from? What were the parameters (if any) you gave the method, and where did you get them?

Patient Zero is out there somewhere.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download