what is interface in c# with example
In C#, an interface defines a contract, specifying methods, properties, events, and indexers that any class or struct implementing it must provide. It's a blueprint for behavior, enabling multiple classes to share common functionality and promoting code reusability.
what is Interface in c#
An interface is a type that defines a set of members (methods, properties, events, and indexers) without providing any implementation.
Example Interface in c#
public interface IAnimal
{
string MakeSound(); // Method declaration (no implementation)
}
// Implement the interface in a class
public class Dog : IAnimal
{
public string MakeSound() // Method implementation
{
return "Woof!";
}
}
// Another class implementing the same interface
public class Cat : IAnimal
{
public string MakeSound() // Method implementation
{
return "Meow!";
}
}
// Use the interface in another class
public class AnimalSound
{
public void PlaySound(IAnimal animal)
{
Console.WriteLine(animal.MakeSound()); // Call the method from the interface
}
}
// Main Program
public class Program
{
public static void Main(string[] args)
{
AnimalSound soundPlayer = new AnimalSound();
Dog dog = new Dog();
Cat cat = new Cat();
soundPlayer.PlaySound(dog); // Output: Woof!
soundPlayer.PlaySound(cat); // Output: Meow!
}
}
No comments:
Post a Comment