Anto Varghese
Anto Varghese

Reputation: 3251

Can we have member variables in Interface?

I read somewhere that interfaces can have member variables.

Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional.

I am not quite understood by what they meant? Any help?

Upvotes: 1

Views: 3272

Answers (3)

Joshua
Joshua

Reputation: 43317

Adding member variables to interfaces would be bringing in MI through the back door.

Not available in .NET, sorry.

I wish it were there though.

Upvotes: 0

JaredPar
JaredPar

Reputation: 755179

What you read is incorrect. Interfaces cannot have member variables.

In VB.Net the only allowable definitions inside an interface are

  • Properties
  • Methods
  • Events
  • Type Definitions (not legal in C#)

I'm not entirely sure what the above paragraph is referring to. Based on the text though it sounds like it's refering to Java. They phrase static and final is most often associated with Java code and not .Net (static and readonly).

Can you give us some more context on it?

Upvotes: 5

spbfox
spbfox

Reputation: 949

If you define a constant like this inside a class MyClass:

public static final int MY_CONSTANT = 1;

you can refer to it from other classes as MyClass.MY_CONSTANT, using the MyClass qualifier. This hints the location of the constant definition.

If you define such a constant in an interface MyInterface, you still can refer to it using MyInterface.MY_CONSTANT. However in the classes implementing MyInsterface you can simply use MY_CONSTANT without "MyInterface" prefix.

It may look convenient (less key strokes), but may lead to confusion because without qualifier (prefix) it is not clear where the constant was originally defined.

Upvotes: 1

Related Questions