I want to implement a generic class AppContextItem with the generic Interface IAppcontextItem. As I want to store multiple AppContextItems inside of a List without knowing the exact type (and also I want to be able to mix multiple typed AppContextItems inside the list). I created another non-generic Interface IAppContextItem. The generic implementation of IAppContextItem should hide the non-generic fields but it somehow doesn’t, because I get an compile error that tells me I need to implement Element with return type object. Is it impossible to do what I want or did I get something wrong?
IAppcontextItem.cs
public interface IAppContextItem
{
string Key { get; set; }
object Element { get; set; }
}
public interface IAppContextItem<T> : IAppContextItem
where T : class
{
new string Key { get; set; }
new T Element { get; set; }
}
AppContextItem.cs
public class AppContextItem<T> : IAppContextItem<T> where T : class
{
private string key = string.Empty;
private T element;
public string Key
{
get { return key; }
set { key = value; }
}
public T Element
{
get { return element; }
set { element = value; }
}
You have to implement both the
T Element andobject Elementproperties. The implementation forobject Elementwill look like:You can then cast it to the correct interface:
This is called Explicit Interface Implementation.
If you want to have a different implementation of
IAppContextItem.KeyandIAppContextItem<T>.Keyyou can use explicit interface implementation like this: