I have a virtual method that returns a collection of items that must be unique. I want to make sure that it will be obvious when overriding the method. What is the best way to do this?
Here is an example, where "Two"
is being returned twice erroneously.
public abstract class Base
{
public abstract IEnumerable<string> GetUniqueNames();
}
public class Derived : Base
{
public override IEnumerable<string> GetUniqueNames()
{
return new List<string> { "One", "Two" };
}
}
public class Subderived : Derived
{
public override IEnumerable<string> GetUniqueNames()
{
return base.GetUniqueNames().Concat(new List<string> { "Two", "Three" });
}
}
I am thinking of returning something like UniqueValueCollection that would throw an exception when a duplicate is attempted to be added. This way other developers will get a hint from name and a descriptive error if they still try to misuse it. Is this a good idea?
PS: I don't need to access the elements by key - it's just an enumerable collection, although UniqueValueCollection<> might use Dictionary<>/HashSet<> behind the scenes.
PPS: maybe a HasSet<> behind an interface? It would be great if it was ordered though.