What is an interface, and what can (and can't) it contain in its most basic form?
Short answer
An interface defines a CONTRACT of members (methods, properties, events, indexers) that implementing classes/structs must provide — traditionally, an interface couldn't contain ANY implementation, only signatures, though modern C# (8+) allows optional default implementations too.
Advertisement
AModel answer
An interface defines a CONTRACT of members (methods, properties, events, indexers) that implementing classes/structs must provide — traditionally, an interface couldn't contain ANY implementation, only signatures, though modern C# (8+) allows optional default implementations too.
public interface IShape {
double CalculateArea(); // no implementation, just a contract
double Perimeter { get; } // property signature only
}
public class Circle : IShape {
public double Radius { get; set; }
public double CalculateArea() => Math.PI * Radius * Radius;
public double Perimeter => 2 * Math.PI * Radius;
}Real-world example
Defining a common IShape contract that Circle, Square, and Triangle all implement independently.
Likely follow-ups
- Can a class implement MULTIPLE interfaces at once, unlike single inheritance from a base class?
Related topics