I've linked my YouTube video below, where I explain interface in C# with a practical example and a fun coding challenge at the end. Below the video, you'll find the actual code featured in the tutorial.
Try solving the coding challenge yourself before checking out the solution provided at the end of this blog - it’s a fantastic way to test your understanding and sharpen your skills! Happy coding! 😊
Actual code featured in the tutorial
using System;
using System.Collections.Generic;
namespace Interface_App
{
internal class Program
{
static void Main(string[] args)
{
List flyingThings = new List
{
new People(),
new Airplane()
};
foreach (var thing in flyingThings)
{
thing.Fly();
thing.Glide();
Console.WriteLine();
}
List speakingThings = new List
{
new People()
};
foreach (var thing in speakingThings)
{
thing.Speak();
Console.WriteLine();
}
}
}
interface IAirActivities
{
void Fly();
void Glide();
}
interface ISpeaking
{
void Speak();
}
public class People : IAirActivities, ISpeaking
{
public void Fly()
{
Console.WriteLine("People who fly airplanes are called pilot.");
}
public void Glide()
{
Console.WriteLine("People can glide in the air using gliders.");
}
public void Speak()
{
Console.WriteLine("People can speak at least one language.");
}
}
public class Airplane : IAirActivities
{
public void Fly()
{
Console.WriteLine("Airplanes are able to fly in the sky");
}
public void Glide()
{
Console.WriteLine("Airplanes can glide with their engines off");
}
}
}
Interface coding challenge solution
Below is the solution to the coding challenge featured in the video.
using System;
using System.Collections.Generic;
namespace InterfaceExcerciseApp
{
internal class Program
{
static void Main(string[] args)
{
IAnimal lion = new Lion();
IAnimal parrot = new Parrot();
IAnimal snake = new Snake();
List animals = new List { lion, parrot, snake};
foreach (IAnimal animal in animals)
{
Console.WriteLine(animal.Eat());
Console.WriteLine(animal.MakeSound());
Console.WriteLine();
}
}
}
public interface IAnimal
{
string Eat();
string MakeSound();
}
public class Lion : IAnimal
{
public string Eat()
{
return "Lions eat meat";
}
public string MakeSound()
{
return "Lion roars";
}
}
public class Parrot : IAnimal
{
public string Eat()
{
return "Parrots eat nuts.";
}
public string MakeSound()
{
return "Parrots sing";
}
}
public class Snake : IAnimal
{
public string Eat()
{
return "Snakes eat rodents.";
}
public string MakeSound()
{
return "Snakes hiss.";
}
}
}
No comments:
Post a Comment