Home > other >  Custom class implementing interface IDictionary<type, type> that could be static?
Custom class implementing interface IDictionary<type, type> that could be static?

Time:10-22

This is a bit Software Engineering and C# question. It seems to me this question will end up all about what c# CAN do so I'll post it here first.

I have a project that has multiple classes that need to access the same dataset. I have created a custom class for that dataset that has a private Dictionary<byte[], MyCustomInterface> instance. The class implements IDictionary<byte[], MyCustomInterface>. For the methods and properties I just wrap the private dictionary methods and properties. I have then added some methods and properties of my own dedicated to my specific needs.

As I said I need access to the custom dictionary and it's data in many classes. I tried making my custom class static but can't because it implements interfaces.

I could make a database in the background but that would be a way heavyweight solution. I have done this before but it ends up being a lot of maintenance.

What other ways would be available to have access to the same set of data/same class from all my classes? I need to be able to serialize/deserialize this custom data set and save the data in a file for retrieval later. I'd prefer to not give up on using Interfaces, they're really handy.

public class EntityDictionary : IDictionary<byte[], IDispenseEntity>
{
    private Dictionary<byte[], IDispenseEntity> _backing = new(new ByteArrayComparer());

    public IDispenseEntity this[byte[] key]
    {
        get => _backing[key]; 
        set => _backing[key] = value;
    }

    public ICollection<byte[]> Keys => _backing.Keys;

    public ICollection<IDispenseEntity> Values => _backing.Values;
    
    ...
    //My custom properties and methods
}

CodePudding user response:

Singleton pattern?

public class EntityDictionary : IDictionary<byte[], IDispenseEntity>
{

    private EntityDictionary() {}
    static EntityDictionary() {}
    private static _instance = new EntityDictionary();
    public static Instance { get { return _instance; }}  

    ...

}

So there is only one dictionary that's shared by all uses, you can;t create your own instance, and are forced to use the single instance.

  • Related