Implement Interfaces in a Project
In object-oriented programming, interfaces define a contract that classes can implement. They specify method signatures and properties that implementing classes must provide. This allows for consistent behavior across different types while enabling flexibility in implementation. In C#, interfaces are defined using the interface
keyword, and classes implement them using the : InterfaceName
syntax.
In this exercise, you will create a console app to define and implement interfaces, including explicit interface implementations, to ensure consistent behavior across various components of an application.
This exercise takes approximately 20 minutes to complete.
Before you start
Before you can start this exercise, you need to:
- Ensure that you have the latest short term support (STS) version of the .NET SDK installed on your computer. You can download the latest versions of the .NET SDK using the following URL: Download .NET
- Ensure that you have Visual Studio Code installed on your computer. You can download Visual Studio Code using the following URL: Download Visual Studio Code
- Ensure that you have the C# Dev Kit configured in Visual Studio Code.
For additional help configuring the Visual Studio Code environment, see Install and configure Visual Studio Code for C# development
Exercise scenario
Suppose you’re a software developer at a tech company working on a new project. Your team needs to define common behaviors across different classes using interfaces. To ensure consistent behavior, you decide to create and implement interfaces, including explicit interface implementations, in a simple console application.
This exercise includes the following tasks:
- Create a new C# project.
- Define an interface with method signatures and properties.
- Implement the defined interface in a class.
- Create another class that implements the same interface with different behavior.
- Demonstrate interface implementation by creating instances of the classes and calling their methods.
- Test the implemented interfaces and their implementations to ensure they work as expected.
Task 1: Create a new C# project
To start, you need to create a new C# project in your development environment. This project will serve as the foundation for implementing interfaces and their respective classes.
- Open Visual Studio Code.
- Ensure that the C# Dev Kit extension is installed.
- Open the terminal in Visual Studio Code by selecting
View > Terminal
. - Navigate to the directory where you want to create your project.
-
Run the following command to create a new console application:
dotnet new console -n ImplementInterfaces
-
Navigate into the newly created project directory:
cd ImplementInterfaces
-
Open the project in Visual Studio Code:
code .
Check your work: Create a new C# project
Ensure that the project has been created successfully by verifying the presence of the Program.cs
file in the project directory. You should also see the project structure in the Visual Studio Code Explorer pane.
Task 2: Define an interface with method signatures and properties
Next, you will define an interface that includes method signatures and properties. This interface will be used to enforce a contract for any class that implements it.
- In the
ImplementInterfaces
project, create a new file namedIPerson.cs
. -
Add the following code to define the
IPerson
interface:public interface IPerson { string Name { get; set; } int Age { get; set; } void DisplayInfo(); }
Check your work: Define an interface
Verify that the IPerson
interface is correctly defined by checking the IPerson.cs
file. The interface should include the Name
and Age
properties, as well as the DisplayInfo
method signature.
Task 3: Implement the defined interface in a class
Now, you will create a class that implements the IPerson
interface. This class will provide concrete implementations for the interface members.
- In the
ImplementInterfaces
project, create a new file namedStudent.cs
. -
Add the following code to implement the
IPerson
interface in theStudent
class. Note that we initialize the properties with default values to avoid nullable warnings:```csharp public class Student : IPerson { public string Name { get; set; } = string.Empty; public int Age { get; set; } = 0;
public void DisplayInfo() { Console.WriteLine($"Student Name: {Name}, Age: {Age}"); } }
Note: In C#, the code
public string Name { get; set; } = string.Empty;
andpublic int Age { get; set; } = 0;
sets default values for the properties (Name
starts as an empty string, andAge
starts as 0). This helps avoid warnings from the compiler about “nullable” issues. If you don’t set these default values (e.g., just usepublic string Name { get; set; }
), your code will still work, but the compiler will warn you that these properties might not be initialized before being used.
Check your work: Implement the defined interface
Ensure that the Student
class correctly implements the IPerson
interface by checking the Student.cs
file. The class should provide implementations for the Name
and Age
properties, as well as the DisplayInfo
method.
Task 4: Create another class that implements different behavior
You will now create another class that implements the IPerson
interface but with different behavior.
- In the
ImplementInterfaces
project, create a new file namedTeacher.cs
. -
Add the following code to implement the
IPerson
interface in theTeacher
class:public class Teacher : IPerson { public string Name { get; set; } = string.Empty; public int Age { get; set; } = 0; public void DisplayInfo() { Console.WriteLine($"Teacher Name: {Name}, Age: {Age}"); } }
In the teacher class the DisplayInfo
method differs from the version in the student class with teh console output starting with “Teacher Name.”
Check your work: Create another class that implements the same interface
Verify that the Teacher
class correctly implements the IPerson
interface by checking the Teacher.cs
file. The class should provide implementations for the Name
and Age
properties, as well as the DisplayInfo
method.
Task 5: Demonstrate interface implementation
In this task, you will demonstrate the use of the interface by creating instances of the Student
and Teacher
classes and calling their methods.
- Open the
Program.cs
file in theImplementInterfaces
project. -
Replace the existing code with the following:
using System; namespace ImplementInterfaces { class Program { static void Main(string[] args) { IPerson student = new Student { Name = "John Doe", Age = 20 }; IPerson teacher = new Teacher { Name = "Jane Smith", Age = 35 }; student.DisplayInfo(); teacher.DisplayInfo(); } } }
Check your work: Demonstrate interface implementation
You should see the dotnet run
output displaying the information for both the student and the teacher, demonstrating the interface implementation.
Task 6: Test the implemented interfaces
Finally, you will test the implemented interfaces and their respective classes to ensure they function correctly.
- Ensure that the
Program.cs
file contains the code to create instances ofStudent
andTeacher
and calls theirDisplayInfo
methods. -
Run the application again using the following command:
dotnet run
- Verify the output to ensure that the information for both the student and the teacher is displayed correctly.
Check your work: Test the implemented interfaces
Confirm that the application runs without errors and displays the correct information for both the student and the teacher. The output should look similar to the following:
Student Name: John Doe, Age: 20
Teacher Name: Jane Smith, Age: 35
In this exercise, you learned how to define and implement interfaces in C# to enforce consistent behavior across multiple classes. By creating a shared interface and implementing it in different classes, you ensured that each class adhered to a common contract while allowing for unique implementations. You also demonstrated the use of interfaces by creating instances of these classes and testing their functionality. This approach is a powerful way to design flexible and maintainable applications in object-oriented programming.
Clean up
Now that you’ve finished the exercise, consider archiving your project files for review at a later time. Having your own projects available for review can be a valuable resource when you’re learning to code. Also, building up a portfolio of projects can be a great way to demonstrate your skills to potential employers.