Mark As Completed Discussion

Interfaces

In C#, an interface is a reference type that defines a contract for other classes to implement. It allows you to define a set of methods, properties, and events that a class must implement. An interface only contains method signatures, properties, and event declarations, without any implementations.

Interfaces play a crucial role in achieving multiple inheritance in C#. C# classes can implement multiple interfaces, which allows them to inherit the behavior of multiple interfaces.

Here's an example of using interfaces in C#:

TEXT/X-CSHARP
1using System;
2
3public interface IPlayable
4{
5    void Play();
6}
7
8public interface IPausable
9{
10    void Pause();
11}
12
13public class MediaPlayer : IPlayable, IPausable
14{
15    public void Play()
16    {
17        Console.WriteLine("Media player is playing...");
18    }
19
20    public void Pause()
21    {
22        Console.WriteLine("Media player is paused...");
23    }
24}
25
26public class Program
27{
28    public static void Main(string[] args)
29    {
30        MediaPlayer mediaPlayer = new MediaPlayer();
31
32        // Play the media
33        mediaPlayer.Play();
34
35        // Pause the media
36        mediaPlayer.Pause();
37    }
38}
CSHARP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment