Um momento
0x40Lesson 5 of 6

Model objects with classes and interfaces

Encapsulate state in classes and describe capabilities with interfaces.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Create a class with properties and explain interface contracts.

A class defines a reference type with data and behavior; an object is an instance. Properties provide controlled access through get and set accessors, while constructors establish valid initial state. An interface describes members a type promises to provide. Code that depends on an interface can work with different implementations. C# 12 also supports primary constructors, while ordinary constructors remain common.

Program.cs · C# 12
1using System;
2
3interface INotifier
4{
5    void Send(string message);
6}
7
8class ConsoleNotifier : INotifier
9{
10    public void Send(string message) => Console.WriteLine(message);
11}
Output
The class provides the interface method.

The I prefix is a common .NET interface naming convention. A class implements an interface with a colon and must provide its required members. Expression-bodied members use => for a single expression.

Key takeaways

  • Classes define types; objects are instances.

  • Properties provide controlled access to state.

  • Interfaces allow interchangeable implementations.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C#

Write C# 12 in the editor and run it against sample input. .NET 8 compiles and runs the code through Wandbox, a free public service; your source and test input are sent there.

Exercise 1

Create a rectangle class

+25 XP

Add a constructor that stores width and height and an Area method. Read two integers, create a Rectangle, and print its area.

  • Three by four
  • Five by two
main.c
Loading editor…

C# 12 code is compiled and run with .NET 8 on Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: