1
interface IA
{
   public const int months = 12;
}

public class A : IA
{
}

Why constants are not allowed in interface?

Vikram Babu Nagineni
  • 3,411
  • 6
  • 25
  • 34
  • 2
    A field is an implementation detail, an interface is a contract that aims to abstract implementation away. – CodesInChaos Oct 05 '13 at 17:05
  • In general one should avoid public fields in favour of public properties with private fields. (except in high performance scenarios) So we'd write your interface as `int X{get;set;}` – CodesInChaos Oct 05 '13 at 17:07
  • 1
    @CodeInChaos, you completely miss the point of properties versus fields. int X { get; set; } is just noise compared with int x. If you aren't making the setter at least internal, if not private, then use a field as it's effectively the same thing. – David Arno Oct 05 '13 at 17:42
  • @DavidArno: Not quite, as a field will mean a change of the public interface, if in any future version the getter and/or the setter has to do anything special, and thus a property is required then. – O. R. Mapper Oct 05 '13 at 18:51
  • 1
    @O. R. Mapper, that just makes me shudder. Having a completely mutable property int X{get;set;} is bad enough, but the idea that might change in the future such that either get or set has side-effects is just plain horrible. If it has to be completely mutable, then I'd be happier having it as a field as I know what it's doing then. – David Arno Oct 05 '13 at 18:54
  • @DavidArno: Who says anything about side-effects? The change might be as little as checking an assigned value, as is the case in many classes from the base class library. Using a field would break encapsulation - not just in the current version, but in any (binary compatible) future versions of the class. – O. R. Mapper Oct 05 '13 at 19:09
  • 2
    This question is not a duplicate of the indicated question; this question is specifically about *constants*. It would be a perfectly reasonable feature to allow constant fields in an interface, eg: `interface I { int Search(); const int NotFound = -1; }` and now it is clear that an implementation should return -1 if the search fails. The reason this feature does not exist is the same reason every other sensible feature does not exist: no one ever implemented it. The design team does not need a reason to NOT implement features. – Eric Lippert Oct 05 '13 at 20:51

0 Answers0