Search code examples
c#type-parameter

C# - Type Parameters in Constructor - No Generics


I have a class that I am trying to do unit tests on. The class is a WCF Service Class. (Making it a generics class is not my goal.)

I have a data access layer (DAL) type (called UserDAL) that is instantiated in many methods. To get these methods under test, I need to get this local variables mocked. (Each instance of UserDAL has method specific value in it, so changing it a class level variable would result in messy code, so I would rather not do that.)

What I am thinking would be nice is to overload the constructor and pass in a type to use in the local methods. The empty param constructor would still create a normal UserDAL, but the overloaded one would have a mock type that implements IUserDAL.

I am not sure of the syntax to say I want to pass in a type. Note that I am not trying to pass in a variable, but a type.

Example:

public class MyWCFClass: IMyWCFClass
{
    private TypeParam _myUserDALType;
    public MyWCFClass()
    {
        _myUserDALType = UserDAL;
    }
    public MyWCFClass(TypeParam myUserDALType)
    {
        _myUserDALType = myUserDALType;
    }

    //methods to use it
    public MyMethod()
    {
        IUserDAL userDAL = new _myUserDALType();
        //Call method in IUserDAL
        userDAL.CreateUser();
    }


    // Several similar methods that all need a different UserDAL go here
    .....
}

So, I don't know what kind of type TypeParam is (I made that up) or if this kind of think is even possible.

If you have a non generics solution that would be great.


Solution

  • You mean Type, using Activator.CreateInstance to create instances:

    public class MyWCFClass: IMyWCFClass
    {
        private Type _myUserDALType;
        public MyWCFClass()
        {
            _myUserDALType = typeof(UserDAL);
        }
        public MyWCFClass(Type myUserDALType)
        {
            _myUserDALType = myUserDALType;
        }
    
        //methods to use it
        public void MyMethod()
        {
            IUserDAL userDAL = (IUserDAL) Activator.CreateInstance(_myUserDALType );
            //Call method in IUserDAL
            userDAL.CreateUser();
        }
    }