TP

# Can't return anonymous type from method? Really?

One of the new features introduced in C# 3.0 which will be available in Visual Studio "Orcas" (currently in CTP version) is anonymous type. Anonymous type is something very similar to tuple type from Cω [1] (which is based on tuple types known from many functional programming languages including F#). Anonymous types are extremely useful in LINQ queries, because it allows you to construct type with several properties without declaring the type (with all the properties). Example of query with anonymous type looks like this:

var q = from c in db.Customers
where c.Country = "Czech Republic"


Ok, it's probabbly not the best example, but it demonstrates the point - you want to return some information from query and you don't need to declare type that contains FullName and Address properties before, because you need it only for this single query (and you want to return only these two fields, so you don't transfer additional data that you don't need from database).

Now let's get to the second point - because anonymous types are really anonymous, you can't use them as return types from methods. This is intentional limitation of C# 3 - if you want to return it from method it should have some name to make the code more readable. In some sitations you can return anonymous type as an object and access it's properties using reflection, but this will be slow (so it's usually better to refactor the code and create named type).

## How is this implemented?

Internally, the runtime still needs to know the type - because everything stays strongly typed. Therefore the compiler generates type to represent the anonymous type and gives it some unique name:

// Sample anonymous type..
var ann = new { City="Prague", Name="Tomas" };


Signature of the class generated by C# compiler looks like this:

[CompilerGenerated]
public sealed class <Projection>f__0
{
// Methods
public <Projection>f__0();
public override bool Equals(object);
public override int GetHashCode();
public override string ToString();

// Properties
public string City { get; set; }
public string Name { get; set; }

// Fields
private string _City;
private string _Name;
}


## Casting to anonymous types

There is one interesting quote in the C# 3.0 specification: "Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and types in the same order will produce instances of the same anonymous type". This implies that when you use two anonymous types with same properties in two different places of same program, the compiler will use same generated class for these two types (this actually isn't true for the May CTP, but in the latest "Orcas" CTP it works as described).

This is interesting fact, because thanks to this it is possible to write the following "little trick" that makes it possible to return instance of anonymous type from method and cast it back to the original type (so you can directly access to properties of the object instead of using reflection). For the casting we need to know the type, but because the type is anonymous it's not that simple, however thanks to the type inference that is used when calling methods you can get the type without writing the actuall type name - you'll just need another variable (or expression) of the same type:

// Method that returns anonymous type as object
object ReturnAnonymous()
{
return new { City="Prague", Name="Tomas" };
}

// Application entry-point
void Main()
{
// Get instance of anonymous type with 'City' and 'Name' properties
object o = ReturnAnonymous();

// This call to 'Cast' method converts first parameter (object) to the
// same type as the type of second parameter - which is in this case
// anonymous type with 'City' and 'Name' properties
var typed = Cast(o, new { City="", Name="" });
Console.WriteLine("Name={0}, City={1}", typed.Name, typed.City);
}

// Cast method - thanks to type inference when calling methods it
// is possible to cast object to type without knowing the type name
T Cast<T>(object obj, T type)
{
return (T)obj;
}


This trick uses type inference algorithm that is used when calling methods. If you create anonymous type with the same properties in second class, the compiler knows the type and can use it as type parameter that is passed to the Cast method. This assigns name of the anonymous type to the generic parameter T and you can cast the value (passed as a first parameter) back to the anonymous type.

So you can return anonymous types from method and use them in another method without reflection (the only overhead is one method call, one created object instance and one type cast). The question is whether you should do this?

## No warranties!

Although this code works quite well (in latest "Orcas" CTP) it is quite risky to use it - first this behavior might change in the final version. Even if this will still work in final version, you can use it only for types in one assembly (two anonymous types from two different assemblies will be internally compiled to two different types that can't be converted using this trick). It also bypasses C# 3.0 limitation that has quite good reason - when you're returning object instead of named type it will make the code less readable and it will be difficult to understand for someone else. For me, it is more an interesting trick than something I'd like to see in my code :-), but if you know of any good reasons for using it, please let me know!