Home > front end >  How to automaticly provide constructors from generic base class in C#?
How to automaticly provide constructors from generic base class in C#?

Time:03-17

So I have a generic base class like this:

class DatabaseDatasourceClassBase<DomainClass>
    where DomainClass : new()
{
    protected DomainClass m_DbObject;

    public AddableDatabaseDatasourceClassBase()
    {
        m_DbObject = new DomainClass();
    }

    public AddableDatabaseDatasourceClassBase(DomainClass initialObject, ISessionWrapper dbSession)
    {
        m_DbObject = initialObject;
        //Do stuff like calling SetSession(dbSession);
    }

    //Several functions and stuff like SetSession(ISessionWrapper dbSession)
}

I also got a lot (>20) of datasource-classes for the use in wpf-datagrids.

class CurrencyDatasource : AddableDatabaseDatasourceClassBase<Currency>
{
    //The constructors look always the same
    public CurrencyDatasource()
        :base()
    {
        
    }

    public CurrencyDatasource(Currency initialExchange, ISessionWrapper dbSession)
        :base(initialExchange, dbSession)
    {
    }

    
    //Following Properties are always different
    public string Name
    {
        get
        {
            return m_DbObject.Name;
        }
        set
        {
            m_DbObject.Name = value;
        }
    }
}

So I wonder if there is a way to avoid having to write the same code (the 2 constructors their call to the base class) in every Datasource class?

or

If this is not possible:

At least define that all classes which are derived from DatabaseDatasourceClassBase have to have these 2 Constructors?

CodePudding user response:

So I wonder if there is a way to avoid having to write the same code (the 2 constructors their call to the base class) in every Datasource class?

Each class must provide their own constructor(s) and define how they wish to call the base class's constructor(s).

At least define that all classes which are derived from DatabaseDatasourceClassBase have to have these 2 Constructors?

Classes must call at least one base class constructor, but there is no way to enforce which one, or require more than one base constructor be hooked up.


That's at least in code.

I guess you could do something crazy with static code analysis.

  • Related