How to pass anonymous types as parameters?

Saeed Neamati picture Saeed Neamati · Jul 8, 2011 · Viewed 135k times · Source

How can I pass anonymous types as parameters to other functions? Consider this example:

var query = from employee in employees select new { Name = employee.Name, Id = employee.Id };
LogEmployees(query);

The variable query here doesn't have strong type. How should I define my LogEmployees function to accept it?

public void LogEmployees (? list)
{
    foreach (? item in list)
    {

    }
}

In other words, what should I use instead of ? marks.

Answer

Tim S. picture Tim S. · Jul 8, 2011

I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:

public void LogEmployees (IEnumerable<dynamic> list)
{
    foreach (dynamic item in list)
    {
        string name = item.Name;
        int id = item.Id;
    }
}

Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.