Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to associate constants with an interface in C#?

Some languages let you associate a constant with an interface:

  • A Java example
  • A PhP example

The W3C abstract interfaces do the same, for example:

// Introduced in DOM Level 2: interface CSSValue {    // UnitTypes   const unsigned short      CSS_INHERIT                    = 0;   const unsigned short      CSS_PRIMITIVE_VALUE            = 1;   const unsigned short      CSS_VALUE_LIST                 = 2;   const unsigned short      CSS_CUSTOM                     = 3;    attribute DOMString       cssText;   attribute unsigned short  cssValueType; }; 

I want to define this interface such that it can be called from C#.

Apparently C# cannot define a constant associated with an interface.

  • What is the usual way to translate such an interface to C#?
  • Are there any 'canonical' C# bindings for the DOM interfaces?
  • Although C# cannot, is there another .NET language which can define constants associated with an interface?
like image 751
ChrisW Avatar asked Oct 05 '12 18:10

ChrisW


People also ask

Can interface be used for constants?

A Java interface can contain constants. In some cases it can make sense to define constants in an interface. Especially if those constants are to be used by the classes implementing the interface, e.g. in calculations, or as parameters to some of the methods in the interface.

Can an interface have constant variables?

Yes, you can keep constants in interfaces.

Can you define constants in an interface C#?

In addition to default method implementations, you can declare constants and static readonly fields in interfaces.

Why constants should not be defined in interfaces?

That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them.


1 Answers

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"; } 
like image 73
David Hyde Avatar answered Sep 28 '22 02:09

David Hyde