How to return anonymous type from c# method that uses LINQ to SQL [duplicate]

Make the anonymous type into a class...

public class Person
{
    public Person() {
    }

    public String Name { get; set; }
    public DateTime DOB { get; set; }
}


Person p = 
    from person in db.People 
    where person.Id = 1 
    select new Person { 
        Name = person.Name,
        DOB = person.DateOfBirth
    }

You cannot type any method in C# to be the explicit type of an anonymous types. They cannot be "named" so to speak and hence cannot appear in metadata signatures.

If you really want to return a value which is an anonymous type there are 2 options

  1. Have the return type of the method be System.Object. You can then do evil casting hacks to get a typed value in another method. This is very fragile and I don't recommend it.
  2. Use a generic method and a type inference trick to get the return type correct. This would require a very interesting signature definition for your approach.

Anonymous types were not really meant to be passed around in this fashion. At the point you need to pass them around between your functions in this manner, you're better off explicitly defining a type.


Using var doesn't make it an anonymous type. Using var just means let this variable be of the type available on the right-hand side of the assignment. It's just short hand. If the thing on the right-hand side is a real class, the variable will be of that type.

For example:

var person = new Person { Name = "bob" };

The person variable is of type Person, even though it used the var keyword.

Anonymous types are created using new { Name = ... }. In this case it's a new, anonymous class. The only thing you can assign it to is a variable defined using var (or object) since there is no existing name to use.

For example:

var person = new { Name = "bob" };

In this case, person is an anonymous type defined at run time.

Generally, as @Chalkey says, if you want to pass the result back to another method, use a named type, not an anonymous one.

If you are forced to use an anonymous type, you'll have to pass it back as an object of type Object, then use reflection to get at it's properties.