Search code examples
c#solid-principles

How to initalize a class that inherits interface?


I'm trying to apply SOLID in my code. I've got a Menu with several options. Every menu has some buttons.I'm making a Interface for the first menu buttons:

interface IConvertToPartListButton
{
    void ConvertToPartList();
}
class BtnConvertToPartList : IConvertToPartListButton
{
   void ConvertToPartList()
   {
        //Do something
   } 
}

After that I implement an interface that inherits those two buttons I created

interface IImportPartsButtons : IConvertToPartListButton,IDeleteIP
{
}

So for every menu I will do that. After that I want to inherit all menu buttons :

interface IButton : IImportPartsButtons,SecondMenuButtons,ThirdMenuButtons
{
}

When I try to make a new instance of the class BtnConverToPartList it's not possible.

 public static IButton GetButton() => new BtnConvertToPartList();

Error:

Cannot implicitly convert type 'MOSOSoftware.BtnConvertToPartList' to 'MOSOSoftware.IButton'.

If I am doing something wrong please write that down, I'm new to programming and I'm still learning. Thank You!


Solution

  • You are doing wrong inheritance. "BtnConvertToPartList" implements "IConvertToPartListButton" but "IButton" is not "IConvertToPartListButton" until you implement "IButton" to "IConvertToPartListButton". Please find the changed code below,

     interface IConvertToPartListButton : IButton
    {
        void ConvertToPartList();
    }
    
    
    interface IImportPartsButtons : IConvertToPartListButton
    {
    }
    
    interface IButton
    {
    }
    
    class BtnConvertToPartList : IConvertToPartListButton
    {
        public void ConvertToPartList()
        {
            //Do something
        }
    }
    

    and the instatntiation,

    public static IButton GetButton() => new BtnConvertToPartList();
    

    Now it should work because BtnConvertToPartList is IButton as well because IButton is IConvertToPartListButton.