Home > Back-end >  Generics in C# class in constructor?
Generics in C# class in constructor?

Time:03-22

I have a C# class with a constructor. The constructor currently requires a logger. The code looks like this:

public class MyClass
{
   private ILogger<MyObject> _logger;

   public MyClass(ILogger<MyOjbect> logger)
   {
     _logger = logger; 
   }
}

I would like ILogger to take a generic, that way I can instantiate an instance of MyClass anywhere I want and pass in any type of ILogger that I want, however, when I change to I'm getting:

The type or namespace 'T' cannot be found. Are you missing a directive or assembly reference?

Meaning, I'd like the code to look like this:

public class MyClass
    {
       private ILogger<T> _logger;
    
       public MyClass(ILogger<T> logger)
       {
         _logger = logger; 
       }
    }

and to create it:

var myClass = new MyClass(ILogger<Something> logger);

CodePudding user response:

You need to do this

public class MyClass<T>
--------------------^^^
{
   private ILogger<T> _logger;

   public MyClass(ILogger<T> logger)
   {
     _logger = logger; 
   }
}

CodePudding user response:

Generic class is the right way to use as mentioned in earlier answer, but in case the generic class is not the way you want it, the you can use dynamic

 public class MyClass
{
    private ILogger<dynamic> _logger;
    public MyClass(ILogger<dynamic> logger)
    {
        _logger = logger;
    }
}

then assume it needs to be instantiated from MyClass1

public class MyClass1
{
    public ILogger<MyClass1> _logger;
    public MyClass(ILogger<MyClass1> logger)
    {
        _logger = logger;
    }
     public void Test()
    {
       // instantiate MyClass 
       var myClass = new MyClass(_logger); 
    }
}
  • Related