C# -Interview Question Anonymous Type
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 sin开发者_高级运维gle 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?).
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.
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.
May be try the examples shown here..they try to do something similar..
http://www.codeproject.com/KB/linq/AnonymousTypeTransform.aspx
http://www.inflecto.co.uk/Inflecto-Blog/post/2009/11/12/IQueryable-Sorting-Paging-Searching-and-Counting.aspx
var list = anony.Select(x=> new Product {
ItemPrice = x.ItemPrice, ItemName = x.ItemName }).ToList();
精彩评论