0
0
CsharpHow-ToBeginner · 3 min read

Can Interface Have Properties in C#? Explained with Examples

Yes, in C# an interface can have properties. These properties only declare the property signature without implementation, and any class implementing the interface must provide the property implementation.
📐

Syntax

An interface property declares a property signature without any implementation. It includes the property type, name, and optionally get and/or set accessors.

Classes implementing the interface must provide the actual property code.

csharp
public interface IExample
{
    int MyProperty { get; set; }
    string ReadOnlyProperty { get; }
}
💻

Example

This example shows an interface with properties and a class implementing them. The class provides the actual property code as required.

csharp
using System;

public interface ICar
{
    string Model { get; set; }
    int Year { get; }
}

public class Car : ICar
{
    public string Model { get; set; }
    public int Year { get; private set; }

    public Car(string model, int year)
    {
        Model = model;
        Year = year;
    }
}

class Program
{
    static void Main()
    {
        ICar myCar = new Car("Toyota", 2020);
        Console.WriteLine($"Model: {myCar.Model}, Year: {myCar.Year}");
    }
}
Output
Model: Toyota, Year: 2020
⚠️

Common Pitfalls

One common mistake is trying to provide property implementation inside the interface, which is not allowed in traditional C# interfaces (before default interface implementations in C# 8.0).

Another is forgetting to implement all interface properties in the class, which causes a compile error.

csharp
/* Wrong: Interface cannot have property body (before C# 8.0) */
public interface IWrong
{
    int Number { get { return 5; } } // Error
}

/* Correct: Only declare property signature */
public interface IRight
{
    int Number { get; }
}

public class CorrectClass : IRight
{
    public int Number => 5; // Implementation provided here
}
📊

Quick Reference

ConceptDescription
Interface PropertyDeclares property signature without implementation
Accessorsget and/or set can be declared
ImplementationClasses must implement all interface properties
Default ImplementationC# 8.0+ allows default implementations in interfaces (advanced)

Key Takeaways

Interfaces in C# can declare properties with get and/or set accessors.
Interface properties only declare the signature; implementation must be in the class.
All interface properties must be implemented by any class that implements the interface.
Trying to implement property bodies inside interfaces is not allowed before C# 8.0.
C# 8.0 and later support default interface implementations, but this is an advanced feature.