How to associate constants with an interface in C#?

To answer your third question:

Although C# cannot, is there another .NET language which can define constants associated with an interface?

C++/CLI allows you to define literal values in an interface, which are equivalent to static const values in C#.

public interface class ICSSValue
{
public:
    literal short CSS_INHERIT = 0;
    literal short CSS_PRIMITIVE_VALUE = 1;
    literal short CSS_VALUE_LIST = 2;
    literal short CSS_CSS_CUSTOM = 3;

    property DOMString^ cssText;
    property ushort cssValueType;
}

You could then access the values via C#:

public static void Main()
{
    short primitiveValue = ICSSValue.CSS_PRIMITIVE_VALUE;

    Debug.Assert(primitiveValue == 1);
}

See this page on MSDN for more details.

Disclaimer: The design decision to disallow constant values in interfaces was a good one. An interface which exposes implementation details is most likely a leaky abstraction. In this example CSS Value Type is probably better off being an enumeration.


C# doesn't allow constants in interfaces because a constant is an implementation facet which theoretically does not belong in a type that only defines a behavior protocol.

I suspect the Java folks allow const fields in interfaces either because an interface is treated internally as some kind of abstract class, or because they needed that to make up for some deficiency in the type system, like enums.

I'm not sure what you mean by "canonical bindings for the DOM interfaces". C# does not run in a browser.

That said, you'll need to put your constants somewhere else, like a struct, or an enum (if they are numeric). Perhaps following some kind of naming convention would help -- if your interface is IFooBar then maybe the struct that contains your constant could be called IFooSetttings or IFooValues or whatever is appropriate.

I don't know any CLR languages other than C# and VB.NET, but I'm pretty sure VB doesn't allow this (although it's been a while).


If you want a place to store your constants I would use a static class:

public static class MyConstants
{
    public const int first = 1;
    public const int second = 2;
    public const string projectName = "Hello World";
}

That is (at least one) common standard.


I added a Get only property and backed it up with a const in the definition.

public interface IFoo
{
    string ConstValue { get; }
}

public class Foo : IFoo
{
    public string ConstValue => _constValue;
    private string _constValue = "My constant";
}