Home > OS >  Initialising Generic class with Values
Initialising Generic class with Values

Time:10-25

I have a generic class of NameMap() (showing code of interest)

public class NameMap<T1, T2>
{
    private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
    private Dictionary<T2, T1> _backward = new Dictionary<T2, T1>();

    public void addBidirectional(T1 modelName, T2 bussinessName)
    {
        _forward.Add(modelName, bussinessName);
        _backward.Add(bussinessName, modelName);
    }

The nameMap should be initiated with values as it is created e.g. (Blue,red) for the forward and (red, blue) for the backward dictionary.

I want to have a setup function within this class e.g:

    public void setUpBusinessNames()
    {
        this.addBidirectional(("blue", "red");
    }

However, as the class is generic the strings conflict with the generic types.

I've though some ways of solving this:

  1. Passing an instantiated object into setUpBusinessNames of type NameMap<String,String>
  2. Possibly restrict the namemap class to strings?

Anyone got a good way to do this?

CodePudding user response:

You could try this way:

public void setUpBusinessNames()
{
   (this as NameMap<string,string>).addBidirectional("blue", "red");
}

But this object must be an instance of NameMap<string, string>.

CodePudding user response:

make the generic class as abstract and then create another class which inherits it like this :

public abstract class NameMap<T1, T2>
{
    private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
    
    private Dictionary<T2, T1> _backward = new Dictionary<T2, T1>();
    
    public void Add(T1 modelName, T2 bussinessName)
    {
        _forward.Add(modelName, bussinessName);
        _backward.Add(bussinessName, modelName);
    }
    
    public abstract void SetUp();
}

public class NameMapString : NameMap<string, string>
{
    public NameMapString () : base() { }

    public override void SetUp()
    {
        Add("blue", "red");
    }
}

this would enforce the type. If you need another type, just create another class and do the same procedure.

  • Related