Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List anonymous type to List of interface [duplicate]

Tags:

c#

.net

Possible Duplicate:
Dynamically implementing an interface in .NET 4.0 (C#)
cast anonymous type to an interface?

Is there a way to "cast" an anonymous type to a specific interface ? I know I can create a class who implement this interface but I don't need this class, I have to return an interface.

I need a solution without third party library

Thanks,

var result =
    (from a in context.TABLE1
     join b in context.TABLE2 on a.Table2Id equals b.Id
     select new
     {
         Table1Field1 = a.Field1,
         Table2Field1 = b.Field1,
         ....
     }).ToList<IMyClass>();

public interface IMyClass
{
    string Table1Field1 { get; set; }
    string Table1Field2 { get; set; }
    string Table2Field1 { get; set; }
}
like image 457
Kris-I Avatar asked Jan 19 '26 12:01

Kris-I


1 Answers

This is impossible. Why? Because an anonymous type is a syntactic sugar. Anonymous types are a design-time feature meaning that compiler will generate an actual type with a very strange name, but it's like any other type after all.

Sadly, C# doesn't have interface auto-implementation. That is, you need to implement an interface in a named type.

UPDATE

Want to workaround this limitation?

You can use inversion of control (either using an API like Castle Windsor or just by hand).

Check this sample code I made just now:

public static class AnonymousExtensions
{
    public static T To<T>(this object anon)
    {
        // #1 Obtain the type implementing the whole interface
        Type implementation = Assembly.GetExecutingAssembly()
                                .GetTypes()
                                .SingleOrDefault(t => t.GetInterfaces().Contains(typeof(T)));

        // #2 Once you've the implementation type, you create an instance of it
        object implementationInstance = Activator.CreateInstance(implementation, false);

        // #3 Now's time to set the implementation properties based on
        // the anonyous type instance property values!
        foreach(PropertyInfo property in anon.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            // Has the implementation this anonymous type property?
            if(implementation.GetProperty(property.Name) != null)
            {
                // Setting the implementation instance property with the anonymous
                // type instance property's value!
                implementation.GetProperty(property.Name).SetValue(implementationInstance, property.GetValue(anon, null));
            }
        }

        return (T)implementationInstance;
    }
}

Design and implement some interface...

// Some interface
public interface IHasText
{
    string Text { get; set; }
}

// An implementation for the interface
public class HasText : IHasText
{
    public string Text
    {
        get;
        set;
    }
}

Now use the whole extension method somewhere!

var anonymous = new { Text = "Hello world!" };
IHasText hasTextImplementation = anonymous.To<IHasText>();

hasTextImplementation will have a HasText implementation instance! Or in other words: Text property will contain Hello world!.

Note that this code can be tweaked in order to support base and abstract classes, but I believe that this is enough to get the basic information to improve it as you want and for your needs.

like image 144
Matías Fidemraizer Avatar answered Jan 21 '26 04:01

Matías Fidemraizer



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!