Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling an implemented interface method in Main c#

I am writting a reusuable program, which contains different sorting algorithms. I want each sorting algorithm to implement a "print to console function".So I implemented an interface:

namespace ConsoleControl
{
    interface IConsoleControlInterface
    {
        void PrintArray(int[] array)
        {
            
        }
    }
}

then, my BubbleSort class implements that interface:

using ConsoleControl;

namespace BubbleSort
{
    public class BubbleSortClass : IConsoleControlInterface
    {

as this is an interface, BubbleSortClass has to have an implementation of interface’s function PrintArray(int[] array):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        void IConsoleControlInterface.PrintArray(int[] array)
        {
            Console.WriteLine("Printing The Array");
            foreach (var item in array)
            {
                Console.Write(item + " ");
            }
        }

But how do I actually call this method in my Main()?
I tried this:

        BubbleSort.BubbleSortClass arrayToBeSorted2 = new BubbleSort.BubbleSortClass(10);
        arrayToBeSorted2.InitializeArray();
        arrayToBeSorted2.PrintArray(arrayToBeSorted2.array);

but the compiler show that the PrintArray function does not exist, how to fix it?

I tried calling it from the object arrayToBeSorted2.PrintArray
I assumed that simple call PrintArray(…) would not work as this function is not marked as static

>Solution :

You’ve explicitly implemented IConsoleControlInterface.PrintArray here. In this case, casting (IConsoleControlInterface)arrayToBeSorted2 will show you the method PrintArray as you expect.

Unless you have specific reasons to explicitly implement an interface, prefer implicit implementation which would just be

void PrintArray(int[] array) {...

within BubbleSortClass. This will eliminate the need to cast the class to the appropriate interface in order to "see" the method.

Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading