+ 3
Can someone give me an interface example ?
6 Answers
+ 2
thanks
+ 2
Kamil, can you help me to understand, why we create this template with interface, if we have to implement all methods, and type them one by one in the classes? we could do the same without it, right?
+ 2
Huh, i need time to digest it:) thanks. i will try in the code playground to understand deeply. it is interesting to pass an interface as an argument!! thank you.
+ 1
public interface ISample
{
string Message { get; }
void Show();
}
public class Sample : ISample
{
public string Message { get; }
public Sample(string message)
{
Message = message;
}
public void Show()
{
Console.WriteLine(Message);
}
}
static void Main(string[] args)
{
ISample s = new Sample("test");
s.Show();
}
output will be test of course. Hope this short sample helps.
+ 1
Yes we could. Yet interfaces are better if we are planning to expand our application. Interface is just a description. We create a class which inherits it to implement concrete logic. We could add another class which would inherit the interface and does other things. Let's say we create now a class with constructor which requires ISample as parameter. it will just use its method to display the message it has. But since we require an object which implements the interface in constructor we know that the passed it has the method so we can invoke it. What is more we can at any time pass any object which inherits the interface as parameter. This is the power of interfaces.
Continuing the sample
public class Sample2 : ISample
{
public string Message { get; }
public Sample2(string message)
{
Message = message;
}
public void Show()
{
Console.WriteLine("from sample2 " + Message);
}
}
public class SampleDisplayer
{
public SampleDisplayer(ISample sample)
{
sample.Show();
}
}
we have to change the Main a little bit now..
class Program
{
static void Main(string[] args)
{
ISample s1 = new Sample("sample 1");
ISample s2 = new Sample2("another sample");
SampleDisplayer d1 = new SampleDisplayer(s1);
SampleDisplayer d2 = new SampleDisplayer(s2);
}
}
Hope this helps to understand.
+ 1
You don't really pass interface. You pass a concrete object which implements the interface as in parameter. And you operate on concrete object but since it inherits interface the object can be cast to it.