Not sure if this may help your use case but you can a base / tag interface with nothing on it
public interface IDataElement {}
and have your Variant Generic Interface inherit from that (as Jon Skeet demonstrated)
public interface IDataElement<out T>
So you can then create a collection of these "objects" with its Contravariant, Non Variant Generic Interface (what a mouth full)
var collection = new List<IDataElement>(){ ... }
and when you take an element you may have to be a bit explicit I suppose but for me that is what C# Type safety is about (C# is very explicit!) and avoid using objects
IDataElement<MyType> value = List.First(x => DataElement == 12);
Or use the slightly frowned upon explicit cast
var element = (IDataElement<MyType>)List.First(x => DataElement == 12);
I was searching for this question because I had a generic method like TTYpe Get<TType>()
because I was kind of messing with Strategy/Visitor pattern. I wanted to ask my provider for a arbitrary thing by using the generic Type as the parameter on the method.
Sounds odd maybe but I could actually just leverage Dependency Injection to inject any number of IDataElement implementations, that knew how to configure them selves based on the provider... all I wanted to do was like
var sqlConnection = tenantProvider.Get<SqlConnection>();
var storageTyep = tenantProvider<StorageProvider>();
And with the power of Generics, Variant Generic Interfaces and Tag Interfaces.. it works great. Strongly typed at the consumer, complete generic implementation.
public TSetting GetSetting<TSetting>() where TSetting : class
{
var sp = tenantSettingsDictionary[typeof(TSetting)];
return sp as TSetting;
}