Some languages let you associate a constant with an interface:
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?
A custom attribute can be used:
The custom attribute class could look like:
Constants can be retrieved using
I added a Get only property and backed it up with a const in the definition.
I use SO all the time but this is my first ever post here. I found this post, trying to solve the same problem. When I saw the post on using a static class (by Servy) it got me thinking about solving this by embedding the Interface inside that static class.
An abstract class will do everything an interface will do (well, apart from pass a
typeof(T).IsInterface
test) and allow constants.The objection to constants (or enums) embedded in interfaces is misplaced. It's a naming issue. Naming constants in the very precise context where they have meaning is better than naming them out of context.
To answer your third question:
C++/CLI allows you to define
literal
values in an interface, which are equivalent tostatic const
values in C#.You could then access the values via C#:
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.
If you want a place to store your constants I would use a static class:
That is (at least one) common standard.