Skip to content

Latest commit

 

History

History
55 lines (38 loc) · 3.1 KB

interface-properties.md

File metadata and controls

55 lines (38 loc) · 3.1 KB
title description ms.date helpviewer_keywords ms.assetid
Interface Properties
Properties can be declared on an interface in C#. This example declares an interface property accessor.
07/29/2022
properties [C#], on interfaces
interfaces [C#], properties
6503e9ed-33d7-44ec-b4c1-cc16c084b795

Interface Properties (C# Programming Guide)

Properties can be declared on an interface. The following example declares an interface property accessor:

:::code language="csharp" source="./snippets/properties/interfaces.cs" id="SnippetDeclareInterfaceProperties":::

Interface properties typically don't have a body. The accessors indicate whether the property is read-write, read-only, or write-only. Unlike in classes and structs, declaring the accessors without a body doesn't declare an auto-implemented property. An interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.

Example

In this example, the interface IEmployee has a read-write property, Name, and a read-only property, Counter. The class Employee implements the IEmployee interface and uses these two properties. The program reads the name of a new employee and the current number of employees and displays the employee name and the computed employee number.

You could use the fully qualified name of the property, which references the interface in which the member is declared. For example:

:::code language="csharp" source="./snippets/properties/interfaces.cs" id="SnippetExplicitImplementation":::

The preceding example demonstrates Explicit Interface Implementation. For example, if the class Employee is implementing two interfaces ICitizen and IEmployee and both interfaces have the Name property, the explicit interface member implementation will be necessary. That is, the following property declaration:

:::code language="csharp" source="./snippets/properties/interfaces.cs" id="SnippetExplicitImplementation":::

implements the Name property on the IEmployee interface, while the following declaration:

:::code language="csharp" source="./snippets/properties/interfaces.cs" id="SnippetCitizenImplementation":::

implements the Name property on the ICitizen interface.

:::code language="csharp" source="./snippets/properties/interfaces.cs" id="SnippetPropertyExample"::: :::code language="csharp" source="./snippets/properties/interfaces.cs" id="SnippetUseProperty":::

Sample output

Enter number of employees: 210
Enter the name of the new employee: Hazem Abolrous
The employee information:
Employee number: 211
Employee name: Hazem Abolrous

See also