1

I want to pass a parameter into a method only for the purposes of logging. The parameter is a type of an event that I'm about to process. I can see two approaches to this, and I'm wondering if either of them is more correct?

private void LogEventProcessing<T>()
{
    _logger.Information($"Started processing of {typeof(T).Name} event");
}
private void LogEventProcessing(Type type)
{
    _logger.Information($"Started processing of {type.Name} event");
}
  • 2
    Both will work, so both are "correct". Whichever one is "better" is a matter of opinion. –  Apr 03 '19 at 15:43
  • as long as you´re just interested in the types name, chose what works for you. – MakePeaceGreatAgain Apr 03 '19 at 15:44
  • The first one is probably better for you because then you don't have to remember to pass in the type every time. You just call the logging function. – Tyler Marshall Apr 03 '19 at 15:45
  • 1
    @TylerMarshall The type would still have to be passed in because it cannot be implicitly determined. There is no parameter of type `T`. The OP could not simply call `LogEventProcessing()`. –  Apr 03 '19 at 15:47
  • @Amy, oh you're right. I was thinking of this as an extension. Then you could use typeof self w/o the caller having to pass it. – Tyler Marshall Apr 03 '19 at 15:50
  • If you are always passing a type T that is an event (i.e., an event object or one derived from it) then why use a generic type at all? Pass the event so that you won't need to rely on reflection and type processing... – Jazimov Apr 03 '19 at 16:30

2 Answers2

1

Using Type parameters is cleaner, there's close Flags being placed on this question that I don't agree with, the reason being that the first is the better choice in the scenario described.

You can use Type Constraints to constrain the Type of the parameter being inserted by the client.

private void LogEventProcessing<T>() where T : Event
{
    _logger.Information($"Started processing of {typeof(T).Name} event");
}

The above method will now only accept classes that inherit from the type Event, it's cleaner, and makes the expectation clear to the client what you're expecting here.

Aydin
  • 15,016
  • 4
  • 32
  • 42
-1

I don't like either of these options. As a client you either have to use reflection to call the generic version or you have to call GetType() on the event before passing it to a logging function. That just seems like your client is too closely coupled with what the logging function is doing. What happens if it wants to log more information about the event? Do you create a new method and pass just that information? Or do you go back to every reference to this method and add a new parameter?

Yuck, either way, yuck. My advice: Don't do either. Pass the event and then get whatever you need from it in the method itself.

Muuski
  • 198
  • 1
  • 10