I have an abstract class with a parameterfull constructor:
public abstract class LoggerAdapterBase<TLogger>
{
protected readonly TLogger _logger;
public LoggerAdapterBase(TLogger logger){
this._logger = logger;
}
}
In other class I have to create concrete class that implements abstract, but have a problem:
public class LoggerManager<TLogger, TLoggerAdapter>: ILoggerManager<TLogger> where TLoggerAdapter: LoggerAdapterBase<TLogger>
{
private readonly TLogger _logger;
public LoggerManager(TLogger logger)
{
this._logger = logger;
}
public LoggerAdapterBase<TLogger> CreateLogger(Configuration configuration)
{
return new TLoggerAdapter(this._logger);
//Line above says: Cannot create an instance of the variable type 'TLoggerAdapter' because it does not have the new() constraint
}
}
I don't know why compiler requires new() constraint because LoggerAdapterBase has a constructor that I use, and I've specified this to constraints, it should see the constructor as well as other methods from LoggerAdapterBase. What's wrong here?
Edit
Thank you for answer, I've solved it. I just made interface instead of abstract class and defined prop Logger. And added constraint new(). Now creating looks so:
return new TLoggerAdapter() { Logger = _logger };
It isn't an ideal implementation because of possible NullReferenceExceptions when create an instance out of the LoggerManager, and unexpected replacing of prop Logger.