Why doesn't IEnumerable anonymous types return List <object> in ToList ()?

Here is the simplified function I want to create:

static List<object> GetAnonList(IEnumerable<string> names) { return names.Select(name => new { FirstName = name }).ToList(); } 

In this block of code, I get a compiler error:

Error CS0029 Unable to implicitly convert the type 'System.Collections.Generic.List <>' to 'System.Collections.Generic.List'

The documentation for anonymous types says that anonymous types are treated as a type object. Why doesn't the C # compiler return a List<object> to names.ToList() ?

Also, why is the following code not causing an error? If List<<anonymous type: string FirstName>> cannot be converted to List<object> , then why can it be converted to IEnumberable<object> ?

 static IEnumerable<object> GetAnonList(IEnumerable<string> names) { return names.Select(name => new { FirstName = name }).ToList(); } 
+5
source share
2 answers

If List<<anonymous type: string FirstName>> cannot be converted to List<object> , then why can it be converted to IEnumberable<object> ?

This is because IEnumerable<T> is covariant, while List<T> is not. This has nothing to do with anonymous types.

If the code you wrote was supposed to work, you could use a List<string> as a List<object> and add something to it so that it doesn't compromise security.

You can make your code work by passing a generic parameter to a ToList call:

 static List<object> GetAnonList(IEnumerable<string> names) { return names.Select(name => new { FirstName = name }).ToList<object>(); } 

But you can do very little with this outside of this method. You cannot access the FirstName property if you are not using reflection.

+8
source

IEnumerable<out T> Document IEnumerable (T)

List<T> List (T) Document

Note that the IEnumerable interface has an β€œout” Generic Modifier that allows you to add a more derived type to IEnumerable.

See out (General Modifier) ​​(link to C #)

0
source

Source: https://habr.com/ru/post/1275382/


All Articles