views:

68

answers:

1

this is not a question as i think its discussion, i know you cant return an anonymous type across methods, when i first used anonymous types i thought it would be really nice to be able to return it across methods and when .net 4 came out and with the edition of the dynamic types i thought there might be a hope in returning an anonymous type through dynamic type like this:

      public static dynamic  getCustomer()
    {
        .....
        var x = from c in customers
                select new {Fname = c.FirstName};

        return x;
    }

and then

static void Main(string[] args)
    {
        dynamic x = getCustomer();
        Console.WriteLine(x.First().Fname);
        Console.ReadKey();
    }

but sadly that doesnt work although it compile good,

i guess the reason why is :

Anonymous types known in compile type and must be wrapped into classes that is KNOWN IN RUNTIME !, now anonymous type carry thier information in the compile time hoping some class will come and take this information to runtime , but dynamic type are unkown in compile time so passing anonymous type through dynamic type force the anonymous type to loss its informations/intellisence, i tried to debug and i could get the data i wanted but i guess it works only in debug mode , or maybe im missing something.

i was wondering if any one got it to work or thought about it ?

+1  A: 

You can return an anonymous type, you just can't declare that you'll do so. You can get round it with a horrible hack.

The reason your code doesn't work is nothing to do with anonymous types - it's to do with extension methods not being found in dynamic typing.

Change to:

Console.WriteLine(Enumerable.First(x).Fname);

and I expect it will work.

Jon Skeet
aw that is great Jon,thanks alot, so now its possible !!!we can return anonymous type no problem !!the drawback is we lose intellisence.
Stacker