Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class inherits generic dictionary<string, IFoo> and Interface

I have a class that inherits a generic dictionary and an inteface

public class MyDictionary: Dictionary<string, IFoo>, IMyDictionary
{
}

the issue is that consumers of this class are looking for the '.Keys' and ".Values" properties of the interface so i added:

    /// <summary>
    /// 
    /// </summary>
    ICollection<string> Keys { get; }

    /// <summary>
    /// 
    /// </summary>
    IEnumerable<IFoo> Values { get; }

to the interface.

Now, the implementation needs to have this as well but when i implement these, i get this error:

"The keyword new is required because it hides property Keys . .. "

so what do i need to do. Should i be adding a "new" in front of these get properties?

like image 369
leora Avatar asked Apr 18 '26 16:04

leora


2 Answers

Another option would be to change the types on the interface to be:

public interface IMyDictionary
{
    /// <summary>
    /// 
    /// </summary>
    Dictionary<string, IFoo>.KeyCollection Keys { get; }

    /// <summary>
    /// 
    /// </summary>
    Dictionary<string, IFoo>.ValueCollection Values { get; }
}

That way the interface is already implemented by the dictionary saving you the trouble of implementing the properties again, and it doesn't hide or cover the original implementation.

like image 172
Cameron MacFarland Avatar answered Apr 21 '26 04:04

Cameron MacFarland


Dictionary<string, IFoo> implements the IDictionary<TKey,TValue> interface which already provides the Keys and Values properties. There shouldn't be a need to create your own properties, but the way to get around the compiler warning is to add the new keyword at the beginning of your property declarations in your class.

like image 41
Scott Dorman Avatar answered Apr 21 '26 04:04

Scott Dorman