I'm working with C# and .NET for some time now and even though I've been working with OOP languages before (Java to be more precise), while working on .NET applications I see interfaces used a lot more than I've seen in Java. I don't have a lot of experience at all so I'm not saying that interfaces are more used in .NET but now I felt the need to get deeper understanding of interfaces and what are the benefits which make people to use them so often.
I've some stuff on the internet, some stuff here, and the explanation that made most sense for me was this - How will I know when to create an interface?.
And here comes my question. I don't expect some magical explanation of interfaces at all, cause I've read enough to see that there is not such thing. I hope that with experience and coding the deeper understanding will come by itself so I decided to try the example pointed as benefit of using the interfaces from the accepted answer in the link. I'll copy-paste it here too :
you have a, b, c, d of 4 different types. all over your code you have something like:
a.Process();
b.Process();
c.Process();
d.Process();
Why not have them implement IProcessable
, and then do
List<IProcessable> list;
foreach(IProcessable p in list)
p.Process();
This will scale much better when you add, say, 50 types of classes that all do the same thing.
The problem is that it seems I haven't got this. After I read it I open my Visual Studio 2010 and tried to recreate the example like this - I made a project and created four classes - a
, b
, c
, d
. All those classes are the same :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class a : ITest
{
public void Test()
{
System.Console.WriteLine("Hi from a");
}
}
}
Just 4 different names and the method Test()
printing the name. Here is the interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
interface ITest
{
public void Test();
}
}
And by what I understand in my Program.cs
I have this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
List<ITest> list;
static void Main(string[] args)
{
foreach (ITest p in list)
p.Test();
}
}
}
Well. It seems that I really got the things wrong. I thought that by implementing the same interface I can automatically get a list of all classes and use them, for example like in my Main()
method above. However I get the following error:
An object reference is required for the non-static field, method, or property
Well, can someone lower the level to me and explain me in terms of this example how I exactly benefit like this by using an interface.