views:

56

answers:

1

I have an interface declared as follows

public interface ILoadObjects<T> where T : class
{
    List<T> LoadBySearch();
}

I then have a class declared as follows

public class MyTestClass : ILoadObjects<MyTestClass>
{
    List<MyTestClass> ILoadObjects<MyTestClass>.LoadBySearch()
    {
        List<MyTestClass> list = new List<MyTestClass>();
        list.Add(new MyTestClass());
        return list;
    }
}

Now what I'd like to do, is use that method defined in the interface against that class without having to know what the class is.

public void ExecuteTestClassMethod()
{
    MyTestClass testObject = new MyTestClass();
    object objectSource = testObject;
    object results = ((ILoadObjects<>)objectSource).LoadBySearch();
    {... do something with results ...}
}

The above obviously doesnt work, so I'd like to know how to do something along the lines of that.

Thanks

+4  A: 

You will have do define a second non-generic interface like this:

public interface ILoadObjects<T> : ILoadObjects where T : class
{
    List<T> LoadBySearch();
}

public interface ILoadObjects
{
    IList LoadBySearch();
}

And declare your class as follows:

public class MyTestClass : ILoadObjects<MyTestClass>
{
    public List<MyTestClass> LoadBySearch()
    {
        List<MyTestClass> list = new List<MyTestClass>();
        list.Add(new MyTestClass());
        return list;
    }

    IList ILoadObjects.LoadBySearch()
    {
        return this.LoadBySearch();
    }
}

The IEnumerable<T> and IEnumerable interfaces work the same way.

Now you can call the ILoadObjects.LoadBySearch method like this:

((ILoadObjects)objectSource).LoadBySearch();
Steven
So I would simply keep the class declaration the same, but when calling the method use the ungeneric interface? is that what your saying?
Jonathan
Thanks :) Trying it out right now
Jonathan
That is exactly what I'm saying. You can't cast an instance of such a type to type `ILoadObjects<>` and use it. You need to explicitly use the generic type. A non-generic base type solves this problem. You can also use reflection, but I think this solution if much nicer.
Steven
Thanks for the help, your answer as correct, though now i see my problem is in the way I am trying to formulate the design.Thanks for the help :)
Jonathan