Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Base Class with Constructor

Tags:

c#

generics

I have a generic class that looks like this:

public class DataServiceBase<T> : Screen where  T : EntityManager, new (){

    private T _entityManager;

    public T EntityManager {
        get {
            if (_entityManager == null)
            {
                _entityManager = new T();
            }
            return _entityManager;
        }
    }

Basically all I am trying to do is create an EntityManager of if it doesn't exist. This actually works fine. However, I need to modify this as T no longer has a parameterizerless constructor. And so I can't use this methodology at all.

But I do need the EntityManager strongly typed at the derived level of the DataService as different entity managers handled different entities.

I am not sure how to resolve this. One alternative I have tried is:

public DataServiceBase(EntityManager entityManager) {
        this._entityManager = entityManager;

    }

In other words, I pass it into the constructor, but now I no longer have the property strong typed.

Greg

like image 337
Greg Gum Avatar asked Jan 04 '13 02:01

Greg Gum


People also ask

Can a generic class have constructor?

A generic constructor is a constructor that has at least one parameter of a generic type. We'll see that generic constructors don't have to be in a generic class, and not all constructors in a generic class have to be generic.

Can base class have constructor?

base (C# Reference)A base class access is permitted only in a constructor, an instance method, or an instance property accessor. It is an error to use the base keyword from within a static method. The base class that is accessed is the base class specified in the class declaration.

Can generic class have constructor C#?

Can we have a generic constructor? No, generic constructors are not allowed.

What is base class constructor?

When objects are constructed, it is always first construct base class subobject, therefore, base class constructor is called first, then call derived class constructors. The reason is that derived class objects contain subobjects inherited from base class.


1 Answers

Just make the constructor argument take the generic type also

public DataServiceBase(T entityManager) {
    this._entityManager = entityManager;

}
like image 137
aqwert Avatar answered Sep 28 '22 09:09

aqwert