0

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

Le Vu
  • 407
  • 3
  • 12
  • 1
    Accessing `((IHasItems)derivedClass).Items` is the same as calling `PrintItems(IHasItems obj)` -- both cast `derivedClass` to `IHasItems`. I'm not sure how you're expecting them to be different? – canton7 Sep 23 '21 at 09:02
  • My real-world problem is I have a method to authorize user permission. The input is user information include delegation. But in some cases, I don't want to include delegation info. Actually, I can clone a new object from user info (without delegation) as I mentioned above. I think if there is another approach. – Le Vu Sep 23 '21 at 09:07
  • 1
    I don't see how your real-world problem relates to the code in your question – canton7 Sep 23 '21 at 09:09
  • I feel like your problem could be formulated differently, depending on the context, because right now, `PrintItems` expect a `IHasItems` object, so it will always get `IHasItems.Items` since it doesn't know what `IHiddenItems` is. This solution cannot work as is. – Kilazur Sep 23 '21 at 09:09
  • @Kilazur: I think so. Thanksfor your explaination. – Le Vu Sep 23 '21 at 09:11
  • @canton7: Items here is the list of delegator information. I try to simplify the problem. – Le Vu Sep 23 '21 at 09:11

0 Answers0