I have a class that contains a list of items (implement IHasItems
). In a specific scenario, I want to hide these items by explicit implement IHiddenItems
to return empty list.
But there is an existing method (PrintItems
- in this case), the input parameter type is IHasItems
. Consequently, the items can not be hidden in the method even if I cast the object to IHiddenItems
.
The reason to try this approach is that I don't want to create a prototype of this object and set it empty in the prototype instance.
public interface IHasItems
{
IEnumerable<string> Items { get; }
}
public interface IHiddenItems : IHasItems
{
new IEnumerable<string> Items { get; }
}
public class Implementation : IHasItems, IHiddenItems
{
public Implementation()
{
Items = new List<string>()
{
"A","B","C"
};
}
public IEnumerable<string> Items { get; }
IEnumerable<string> IHiddenItems.Items { get; } = new List<string>(); // Empty
}
static class Program
{
static void Main()
{
Implementation derivedClass = new Implementation();
Console.WriteLine($"Implementation: {derivedClass.Items.Count()}");
Console.WriteLine($"IHasList: {((IHasItems)derivedClass).Items.Count()}");
Console.WriteLine($"IEmptyList: {((IHiddenItems)derivedClass).Items.Count()}");
PrintItems(((IHiddenItems)derivedClass));
Console.Read();
}
public static void PrintItems(IHasItems obj)
{
Console.WriteLine($"PrintItems method: {obj.Items.Count()}");
}
}
Result
Implementation: 3
IHasList: 3
IEmptyList: 0
PrintItems method: 3
Expected
Without modify PrintItems
, it should display to console PrintItems method: 0