[C #] How to pass anonymous types as parameters.

Heitor Helmer Herzog
1 min readMar 20, 2017

--

Considering the following example:

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

From the employee list we select 2 fields and give the name of name and id.
This returns a list with only this 2 values, instead of all fields
From the employee list.
But how do we pass the query variable to another method if we do not know the type?
Very simple, we just have to say that the field type is dynamic,
As in the following example:

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

-Dynamic: The information is known only at runtime and can be
applied to properties, methods return, parameters, objects finally to EVERYTHING.

--

--

Heitor Helmer Herzog
Heitor Helmer Herzog

Written by Heitor Helmer Herzog

Software developer, In love with games and the industry. Let’s code! About me: www.linkedin.com/in/heitorhherzog

No responses yet