views:

94

answers:

1

Hello All I am new user of interface. My problem is i have create a Generic class which have two parameter one is object type another is interface type. Now within class i can cast object using Reflection but i am not getting the way to cast interface.

+1  A: 

Are you looking for something like

public class Factory<TClass, TInterface> where TClass : TInterface, new()
{
    public TInterface Create()
    {
        return new TClass();
    }
}

The 'where TClass : TInterface, new()' is the part where the relation between TClass and TInterface is set up. If you leave out TInterface then you will be unable to cast to the interface.

Which then can be invoked like

var factory = new Factory<MySuperService, IService>();
IService service = factory.Create();

Please supply code to illustrate the problem if this does not solve your problem.

HakonB
Thanks Hakon, I am really looking like this.
Pankaj