Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Anonymous Type

I am using a trick to return Anonymous Type but, i m not sure whether it will work in all scenario. If there is any problem using this trick plz let me know so that i will not use this code in my project

class A
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class B
{
    public int AID { get; set; }
    public string Address { get; set; }
}

private List<object> GetJoin()
{
    var query = from a in objA
                join b in objB
                on a.ID equals b.AID
                select new { a.ID, a.Name, b.Address };
    List<object> lst = new List<object>();
    foreach (var item in query)
    {
        object obj = new { ID = item.ID, Name = item.Name, Address = item.Address };
        lst.Add(obj);
    }
    return lst;
}
T Cast<T>(object obj, T type)
{
    return (T)obj;
}

//call Anonymous Type function
foreach (var o in GetJoin())
{
    var typed = Cast(o, new { ID = 0, Name = "", Address = "" });
    int i = 0;
}
like image 768
Ulhas Tuscano Avatar asked Aug 23 '26 17:08

Ulhas Tuscano


1 Answers

Yes, that's guaranteed to work so long as everything is within the same assembly. If you cross the assembly boundary, it won't work though - anonymous types are internal, and the "identity" is based on:

  • Assembly it's being used in
  • Properties:
    • Name
    • Type
    • Order

Everything has to be just right for the types to be considered the same.

It's not nice though. For one thing, your GetJoin method can be simplified to:

return (from a in objA
        join b in objB
        on a.ID equals b.AID
        select (object) new { a.ID, a.Name, b.Address })
       .ToList();

... and for another, you've lost compile-time type safety and readability.

I think you'd be a lot better off creating a real type to encapsulate this data. Admittedly it would be lovely if we could create a named type which was the equivalent to the anonymous type, just with a name... but that's not available at the moment :(

like image 119
Jon Skeet Avatar answered Aug 26 '26 08:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!