2

Is there a way to declare a vaiable for an open generic type?

Given: There is a generic class Logger that users get from a factory method. Is there a way to have a variable that can hold ANY logger?

Right now Logger inherits from Logger ONLY for being able to declare a variable for an instance without caring what type is logged there.

I use MEF, and in the exports I can use a syntax like [Export(typeof(Logger<>))] to export a generic type... (specifying the exact type on import) so there is some support for open types (at least in typeof). What I need now is a syntax like

Logger<> Logger { get; set; }

Any possibility to do something like that? This particular syntax gets me "Type needed".

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • @Lasse: I guess because `myObject.Log(something)` would yield a compilation error (i.e. the variable is not *only* used to store the reference). `dynamic` would be an option, but then you'd lose compile-time syntax checking. – Heinzi Nov 09 '11 at 11:24
  • That is exactly the thing. I ask the logging service for Logger of type X (for config), but I am not interested in logging to a specific genric type, all the stuff is part of the base. I sometimes may pass the logger around (subclasses etc.) and they dont need to know. I try to avoid (here and in other scenarios) the base class JUST for having one. – TomTom Nov 09 '11 at 11:26
  • Then an interface is the way to go. Isolate out the functionality you need into an interface and use that instead. – Lasse V. Karlsen Nov 09 '11 at 14:17

1 Answers1

2

If Logger's type parameter is covariant, i.e., if it is declared with an out modifier, then you can just use Logger<object>.

IEnumerable<object> = new List<string>; // this works, because IEnumerable is covariant

If Logger's type parameter is not covariant, i.e., if you use it as an input parameter somewhere, e.g. Log(T dataToLog), then implementing a common interface (or using a common base class) seems to be the only way to achieve your goal.

Heinzi
  • 167,459
  • 57
  • 363
  • 519