Jose Belisario
Jose Belisario

Reputation: 57

Get class property depending on generic interface

Lets say i have this:

public interface IMyInterface<T>
{
}

public class MyClass
{
    public IMyInterface<Foo> Foos {get; set;}
    public IMyInterface<Bar> Bars {get; set;}
}

I want to have a method like this one

MyClass.Interfaces<T>()

Which will return MyClass.Foos or MyClass.Bars Depending on T value. How i do that? It's very similar on how EF works.

Upvotes: 2

Views: 73

Answers (2)

Slava Utesinov
Slava Utesinov

Reputation: 13488

public class MyClass
{
    public IMyInterface<Foo> Foos { get; set; }
    public IMyInterface<Bar> Bars { get; set; }

    public IMyInterface<T> Interfaces<T>()
    {
        var property = GetType().GetProperties()
            .Where(x => x.PropertyType.Name.StartsWith("IMyInterface")
                        &&
                        x.PropertyType.GenericTypeArguments.Contains(typeof(T)))
            .FirstOrDefault();

        if (property != null)
            return (IMyInterface<T>)property.GetValue(this);
        return null;
    }
}

Upvotes: 0

Paolo Tedesco
Paolo Tedesco

Reputation: 57192

It requires some plumbing and casting, but you could do that with a dictionary:

public interface IMyInterface<T> {
}
public class Foo { }
public class Bar { }

public class MyClass {

    Dictionary<Type, object> myInterfaces = new Dictionary<Type, object>();

    public IMyInterface<Foo> Foos {
        get { return (IMyInterface<Foo>)myInterfaces[typeof(Foo)]; }
        set { myInterfaces[typeof(Foo)] = value; }
    }
    public IMyInterface<Bar> Bars {
        get { return (IMyInterface<Bar>)myInterfaces[typeof(Bar)]; }
        set { myInterfaces[typeof(Bar)] = value; }
    }

    public IMyInterface<T> Interfaces<T>() {
        return (IMyInterface<T>)myInterfaces[typeof(T)];
    }

}

Upvotes: 1

Related Questions