C#, Am I on the right path of understanding the advantages of an interface? via /r/learnprogramming


C#, Am I on the right path of understanding the advantages of an interface?

I've been studying programming for about two weeks now and the concept of an interface is mostly useless to me… I'm a bit obsessed with figuring out their purpose.

So, I've discovered from research that when using an interface you can write a personalized method for that class since it's using the interface:

interface IActionsofAnimal { void Speak(); } class Program { static void Main(string[] args) { var c = new Cat(); var d = new Dog(); c.Speak(); d.Speak(); } } class Animal { internal void PerformAction(IActionsofAnimal action) { if(action is Cat) { Console.WriteLine ("I am a cat, Meow!"); } if (action is Dog) { Console.WriteLine("I am a dog, Woof!"); } } } class Cat : Animal, IActionsofAnimal { public void Speak() { PerformAction(this); } } class Dog : Animal, IActionsofAnimal { public void Speak() { PerformAction(this); } } 

}

The result was, using the interface I was able to write a single line of code to pass "THIS" to the main base class, which had a special conditional IF statement that checked to see if it was a Cat or Dog, then did the "speak" action.

Is this is what an interface is for?

Submitted July 10, 2017 at 10:47PM by yubario
via reddit http://ift.tt/2tI3fk0

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s