Al2110
Al2110

Reputation: 576

Creating an instance of generic class, how to easily set the type to the calling class

I have a generic class LoggerHelper<T>. There are properties in many different classes in the application, whose values are to be set to instances of LoggerHelper. In the constructors of these classes, this property will be set. For example:

public class Importer
{
    ILogger _logger;

    public Importer()
    {  
        this._logger = new LoggerHelper<Importer>();
    }
}

How can I avoid specifying the type each time? Is there are suitable pattern for this?

Upvotes: 0

Views: 60

Answers (1)

Dmitry
Dmitry

Reputation: 14059

You could use a factory method, thus a type could be inferred by the compiler.


Static method

public static class LoggerHelperFactory
{
    public static LoggerHelper<T> Create<T>(T instance)
    {
        return new LoggerHelper<T>();
    }
}

Then you can call it as:

_logger = LoggerHelperFactory.Create(this);

Extension method

public static class LoggerHelperFactoryExtensions
{
    public static LoggerHelper<T> CreateLogger<T>(this T instance)
    {
        return new LoggerHelper<T>();
    }
}

Usage:

_logger = this.CreateLogger();

Upvotes: 2

Related Questions