views:

125

answers:

2

Recently i was asked to prove the power of C# 3.0 in a single line( might be tricky)

i wrote

new int[] { 1, 2, 3 }.Union(new int[]{10,23,45}).
ToList().ForEach(x => Console.WriteLine(x));

and explained you can have (i) anonymous array (ii) extension method (iii)lambda and closure all in a single line.I got spot offer.

But.....

The interviewer asked me how will you convert an anonymous type into known type :(

I explained

public class Product
{
    public double ItemPrice { private set; get; }
    public string ItemName { private set; get; }
}


var anony=new {ItemName="xxxx",ItemPrice=123.56};

you can't assign product a=anony;

The interviewer replied there is 200% chance to do that if you have a small work around.I was clueless.

As usual,I am waiting for your valuable reply(Is it possible?).

+1  A: 

You're right, you can't make this assignment:

product a=anony;

MSDN: Anonymous Types (C# Programming Guide)

An anonymous type cannot be cast to any interface or type except for object.

Jay Riggs
A: 

Maybe something like this:

class Program
{
    static T Cast<T>(object target, T example)
    {
        return (T)target;
    }

    static object GetAnon()
    {
        return new { Id = 5 };
    }

    static void Main()
    {
        object anon = GetAnon();
        var p = Cast(anon, new { Id = 0 });
        Console.WriteLine(p.Id);
    }
}

Remark: never write or rely on such a code.

Darin Dimitrov
No I don't think that will work. While both anonymous types have the same structure they will still be different Types.
justin.m.chase
@just in case, did you actually tested this example or are you assuming things from the top of your head? Those two will be exactly the same type generated and reused by the compiler. Do you think that if those were two different types the cast would be possible? Do you know how casting works in .NET? Have you opened the generated assembly with reflector and actually analyzed that there's a single type generated? From your comment it seems that the answer to all those questions is negative.
Darin Dimitrov