0

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);
3
  • 1
    It's always best to read the docs when learning a new part of the language. Microsoft docs these days are pretty good. Commented Mar 21, 2022 at 22:19
  • You can never just use made up types. You always have to declare them. Where have you declared T? Commented Mar 21, 2022 at 22:44
  • When you post questions about generics, make sure that any non code mentions of <Something> in angle brackets are surrounded by backticks ` otherwise they get interpreted as html tags and disappear, making for quite confusing reading Commented Mar 22, 2022 at 6:11

1 Answer 1

6

You need to do this

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

   public MyClass(ILogger<T> logger)
   {
     _logger = logger; 
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

And maybe ILogger<MyClass<T>>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.