Linq Anonymous return types

21 Jan

I have decided to make a post about LINQ anonymous types with respect to typing after talking to some colleagues. Below I compare 2 LINQ statements, the first being with an anonymous type being returned, the second with a specified type being returned.

Anonymous type:

IList<Window> windows = new List<Window>();

var query = from window in windows

where window.Visibility == Visibility.Hidden

select new

{

Visibility = window.Visibility,

Title = window.Name

};

image

Specified Type:

IList<Window> windows = new List<Window>();

var query = from window in windows

where window.Visibility == Visibility.Hidden

select new myType

{

Visibility = window.Visibility,

Title = window.Name

};

image

Comparing the two return types shown in both of the images, we can see that both return the same data. The thing we cannot see is that an anonymous type is scoped to the method that the LINQ statement is in. This means that we can’t pass query off to another method unless we extract the data we want to a non anonymous type.

Advertisements

2 Responses to “Linq Anonymous return types”

  1. rhwilburn February 22, 2009 at 8:11 am #

    Note that the anonymous type is scoped to the method it is in because the implicit var typing is only able to be used in the method. For more info see: http://www.anastasiosyal.com/archive/2007/11/27/C-3.0-Anonymous-type-support-is-incomplete.aspx

  2. Kirk Jackson February 22, 2009 at 11:57 pm #

    It’s icky, but you can exploit a compiler feature that reuses the definitions of anonymous types if they match:

    http://blogs.msdn.com/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx

    Kirk

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: