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):
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
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!