How to declare variable for open generic type? Possible?

1.4k views Asked by At

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".

1

There are 1 answers

0
Heinzi On BEST ANSWER

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.