Junior — Middle
Can you declare constant values inside an interface, and how does it affect design?
sobes.tech AI
Answer from AI
In C#, interfaces are not intended for storing constant values. Before C# 8.0, it was not possible to declare fields or constants inside interfaces—only method, property, event, and indexer declarations.
Starting with C# 8.0, interfaces support default implementations, but declaring constants directly inside an interface is still not allowed. Instead, it is common to use:
- Static classes with constants or static readonly fields.
- In an interface, you can declare static properties with default implementations (from C# 8.0), but this is not exactly the same as constants.
Impact on design:
- Constants in interfaces can violate the principle of separation of concerns, as an interface should describe behavior, not store data.
- It is better to keep constants in separate classes or enums to ensure architectural cleanliness and ease of maintenance.
Example of a proper approach:
public static class Constants
{
public const string ApiUrl = "https://api.example.com";
}
public interface IService
{
void Execute();
}
Thus, declaring constants inside an interface is not recommended and is technically restricted.