2

How can i call a method from a static class passing a type of dynamic in generic. Here is my static class:

public static class Log<T>
{
    private readonly static ILog Logger = LogManager.GetLogger(typeof(T));

    public static void LogInfo(string message)
    {
        Logger.Info(message);
    }
}

I want to call LogInfo like this:

Log<myObject.GetType()>.LogInfo("Some String");

My question is about how to pass a type of myObject in Generic, because the type of this object is dynamic.

4
  • 3
    It's not at all clear what you mean by "passing a type of dynamic in generic". Commented Jun 17, 2011 at 13:06
  • You have an interface named ILog and a class named Log that doesn't implement ILog. I'd advise against that. Commented Jun 17, 2011 at 13:27
  • @Jason I will review that, thanks... Commented Jun 17, 2011 at 13:33
  • @Jason What you suggest? Commented Jun 17, 2011 at 13:34

1 Answer 1

4

I want to call LogInfo like this:

Log<myObject.GetType()>.LogInfo("Some String");

Why? Why don't you just do this:

public static class Log {
     private static readonly Dictionary<Type, ILog> loggers =
         new Dictionary<Type, ILog>();

     public static void LogInfo(Type type, string message) {
          var logger = Log.GetLoggerForType(type);
          logger.Info(message);
     }

     public static void LogInfo<T>(string message) {
          LogInfo(typeof(T), message);
     }

     private static ILog GetLoggerForType(Type type) {
          ILog logger;
          if(!loggers.TryGetValue(type, out logger)) {
               logger = LogManager.GetLogger(type);
               loggers.Add(type, logger);
          }
          return logger;
     }
}

Note that this is not, Not, NOT thread safe. I wanted to communicate the idea.

Then:

Log<myObject.GetType()>.LogInfo("Some String");

can be replaced by

Log.LogInfo(myObject.GetType(), "Some String");

or you can even go one step further and add an overload that allows you to say

Log.LogInfo(myObject, "Some String");

(just call object.GetType in LogInfo).

Sign up to request clarification or add additional context in comments.

Comments

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.