What is the advantage of using dynamic type in the below code?
public static List<dynamic> GetEmployees()
{
List<Employee> source = GenerateEmployeeCollection();
var queryResult = from employee in source
where employee.Age > 20
select new { employee.FirstName, employee.Age };
return queryResult.ToList<dynamic>();
}
And when would you go for returning a List<dynamic>.
Is to avoid creating types which would be used only very rarely?
Using anonymous types is great if you're making a query and only you are consuming the results in your method.
In this case, you're returning the data from your method. When returning data from a method, you want the consumer to know exactly what to expect (which they obviously don't with a dynamic type). Therefore, using a dynamic type is certainly not a good idea.
This clearly is a misuse of dynamic keyword - it should be used ONLY for object instances for which the type cannot be defined at the time of coding (which is e.g. the case when interacting with dynamic languages like Python). The author was just too lazy to define a type that he could return from the method.
Instead, the above code should be changed to this:
public class Person
{
public string FirstName { get; private set; }
public int Age { get; private set; }
public Person(string firstName, int age)
{
FirstName = firstName;
Age = age;
}
}
...
public static List<Person> GetEmployees()
{
List<Employee> source = GenerateEmployeeCollection();
var queryResult = from employee in source
where employee.Age > 20
select new Person(employee.FirstName, employee.Age);
return queryResult.ToList();
}
Regarding ToList(): The call to ToList() makes sense, since it 'materializes' the result of the previous LINQ query. Otherwise, the query would defer execution until actually iterated - and this is mostly not desirable in such scenarios as above (but note that you can drop the type argument here, it's inferred by the compiler anyway).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With