I’m not sure how to go about this…
I have a class that performs various functions:
public abstract class EntityBase { ... }
public interface ISomeInterface<T> where T : EntityBase, new() { ... }
public class SomeClass<T> : ISomeInterface<T> { ... }
I’m trying to have a cache of these in a non-generic class:
public class MyClass
{
//Not sure how to do this
private ConcurrentDictionary<?, ISomeInterface<?>> Cache { get; set; }
}
The problem is that EntityBase is abstract and can not do new(), The ISomeInterface expects a class that is based off EntityBase and does new(). Is there any way to do what I’m wanting to do?
Update: I realized that for the TKey I can use Type, but I still am not sure what to put for the ISomeInterface.
Firstly, I think you meant to use
ConcurrentDictionarysince you have a key/value pair.Secondly, you can do it similar to ICloneable. ICloneable has a method that returns an
Objectinstead of a T.Since it’s private you can manage it internally and cast it as needed. Obviously you’ll have to make sure any function calls have a typeparam definition, for example:
Also, even if the property had another modifier (public, internal, protected) you could add comments to callers that the Object is a generic type of ISomeInterface where T is a EntityBase, new(). Then, they simply have to cast however they need to.
You can also have generic methods on the non-generic class to get the cached item as a generic type: