user1703858
user1703858

Reputation: 11

Base class type of the derived classes, Generics - .net

I read about contra and covariance problem and it looks like my code falls into that category. I just want to confirm whether i am doing something else wrong. I am using VS 2005 (company policy..)

I have a few classes as below:

entityBase{}
        entity1 : entityBase {}
        entity2 : entityBase {}

I have another set of classes as below:

dalBase<T> where T: entityBase {}
        entity1Dal : dalBase<entity1>{}
        entity2Dal : dalBase<entity2>{}

Now, I want to have a factory method to return the dal classes based on the parameter - like below:

public xxxType GetDalClass(pType) {
     if (pType == "1") return new entity1Dal();
     if (pType == "2") return new entity2Dal();
    }

My question: What should be the return type of this method - in other words, is there a common base class for entity1Dal and entity2Dal?

I tried dalbase and it did not work.

Thanks, Saravana

Upvotes: 0

Views: 113

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

is there a common base class for entity1Dal and entity2Dal?

Only object, really. One common way of getting round this is to split your DalBase<T> class in half - a generic type and a non-generic type which the generic type derives from:

public class DalBase
{
    // Any members which *don't* need to know about T
}

public class DalBase<T> : DalBase
{
    // T-specific members
}

Then you can change your method return type to the non-generic DalBase class.

Another option is to do the same sort of thing, but make the non-generic part an interface instead of a base class. The generic class would implement the interface and have T-specific members.

Upvotes: 2

Related Questions