This is a relatively straight forward question. But I was wondering what the correct usage is for accessing a method inside a separate project through the use of an interface.>
Interfaces are basically a contract that all the classes implementing the Interface should follow. They looks like a class but has no implementation.
In C# Interface names by convention is defined by Prefixing an 'I' so if you want to have an interface called shapes, you would declare it as IShapes
Improves code re-usabilityLets say you want to draw Circle, Triangle.
You can group them together and call them Shapesand have methods to draw Circle and Triangle
But having concrete implementation would be a bad idea because tomorrow you might decide to have 2 more Shapes Rectangle & Square. Now when you add them there is a great chance that you might break other parts of your code.
With Interface you isolate the different implementation from the Contract
Usage Scenario Day 1
You were asked to create an App to Draw Circle and Triangle
interface IShapes
{
void DrawShape();
}
class Circle : IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to Draw a Circle");
}
}
class Triangle : IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to draw a Triangle");
}
}
static void Main()
{
List shapes = new List();
shapes.Add(new Circle());
shapes.Add(new Triangle());
foreach(var shape in shapes)
{
shape.DrawShape();
}
}
Usage Scenario Day 2
If you were asked add Square and Rectangle to it, all you have to do is create the implentation for it in class Square: IShapes and in Main add to list shapes.Add(new Square());