1

Maybe a simple question but I have a List<object> that I use to return just a handful of properties from my full User class, like first name, last name, phone number.

But my question is why does this work....

public List<object> GetObject(IQueryable query)
{
   // ...
   List<object> smallObj = query.Select(u => GetSmallUser(u)).ToList(); 
   // ...
}

private object GetSmallUser(User user)
{
   return new{
      FirstName = user.FirstName,
      LastName = user.LastName,
      Phone = user.PhoneNumber
   }
}

And this doesn't work...

public List<object> GetObject(IQueryable query)
{
   // ...
   List<object> smallObj = query.Select(u => new
   {
      FirstName = u.FirstName,
      LastName = u.LastName,
      Phone = u.PhoneNumber
   }).ToList(); 
   // ...
}

The later is saying that it convert List of anonymous type to a list of object. Shouldn't those be returning the same thing?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
John
  • 1,808
  • 7
  • 28
  • 57
  • 2
    No, you also can't return a `new List { "foo" }`. Anyway you shouldn't be using `dynamic` to _"return just a handful of properties"_, create a model / DTO that represents the subset. – CodeCaster May 01 '17 at 15:31
  • 1
    Just to piggy back on the duplicate question pointer. The issue is that the latter code attempts to cast a `List` to `List` which is not legal (see duplicate question link). The first code performs individual casts on each item from `AnonymousType` to `Object` (which _is_ legal) inside the method, and then produces a `List`. EDIT: Imagine if the second code read instead as: `query.Select(u => new { ... }).Select(anonType => (object)anonType).ToList()` This is basically the same thing; casting individual items rather than the entire list. – Chris Sinclair May 01 '17 at 15:34
  • @CodeCaster Care if I ask why it would be bad to use dynamic? It's not clear from the example I gave but this is being returned to the front-end for displaying just that subset. So this is the extent of manipulation of that object – John May 01 '17 at 15:39
  • 3
    @John It means you lose all static type checking that you could have had for the benefit of 30 seconds of time writing an actual class to use, dramatically reducing the odds of errors, and making the code that consumes the method *dramatically* easier to write and maintain. If you, even once, have to go and look up what the name of a property is so you ensure you match it exactly you'll have spent more time than had you created an actual class to use. There's basically no context in which you come out ahead doing what you're doing. – Servy May 01 '17 at 15:43

0 Answers0