C#C
C#3y ago
Jona4Play

✅ Issues with interfaces and generic classes

I want to create a general-practise chemistry model in C#. I have created some basic objects and created a few interfaces to specify the interactions between the classes. Now I have an issue when trying to create an instance with a generic class only allowing a certain interface.

I have attached a picture to make the relations a bit clearer. Now for the issue

Compound implements ISolute as well as IAmount
I now pack it into the Mol class which looks like this
public class Mol<IAmount>
{
    public double Amount { get; set; }
    public required IAmount Compound { get; set; }

    public static Mol<IAmount> Of(IAmount compound, double amount)
    {
        return new Mol<IAmount>() { Amount = amount, Compound = compound };
    }
}


Which works fine since compound implements it.
Now I want to create a solution out of it with this method of the solution class:
    public static Solution Of(Mol<ISolute> solute, Volume<ISolvent> solvent)
    {
        return new Solution() { Solute = solute, Solvent = solvent };
    }

Where the problem arises of the ISolute interface not corresponding with the type Compound eventhough ISolute is implemented by Compound and inherits from IAmount
General.png
Was this page helpful?