How to pass anonymous types as parameters?
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.
Solution 1:
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.
Solution 2:
You can do it like this:
public void LogEmployees<T>(List<T> list) // Or IEnumerable<T> list
{
foreach (T item in list)
{
}
}
... but you won't get to do much with each item. You could call ToString, but you won't be able to use (say) Name
and Id
directly.