SlappingTheBass12
SlappingTheBass12

Reputation: 377

Generics in C# class in constructor?

I have a C# class with a constructor. The constructor currently requires a logger<myObject>. 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<T> that I want, however, when I change <MyObject> to <T> 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);

Upvotes: 0

Views: 91

Answers (1)

pm100
pm100

Reputation: 50110

You need to do this

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

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

Upvotes: 6

Related Questions