+ 3

Can someone give me an interface example ?

29th Oct 2016, 10:05 PM
Victor Dantas
Victor Dantas - avatar
6 Réponses
+ 2
thanks
30th Oct 2016, 3:30 PM
Victor Dantas
Victor Dantas - avatar
+ 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?
8th Nov 2016, 9:12 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar
+ 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.
18th Nov 2016, 7:26 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar
+ 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.
30th Oct 2016, 1:52 PM
Kamil Kosyl
Kamil Kosyl - avatar
+ 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.
18th Nov 2016, 7:17 PM
Kamil Kosyl
Kamil Kosyl - avatar
+ 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.
18th Nov 2016, 7:34 PM
Kamil Kosyl
Kamil Kosyl - avatar