Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an interface have static variables in C#

It might be a silly question, I appreciate if someone can help me understand it.

  1. Can an interface in C# can have static variables?

  2. If the interface itself need to be static to declare static variables inside?

  3. How the implementation goes for static variables(Or say property) within an interface, when we implement in a class?

Some examples and perspicuous explanation would be greatly appreciated.

like image 903
Jasmine Avatar asked Oct 21 '13 13:10

Jasmine


People also ask

Can an interface have static variables?

Interface variables are static because Java interfaces cannot be instantiated on their own; the value of the variable must be assigned in a static context in which no instance exists.

CAN interface have static variables in C#?

No, an interface in C# can't declare fields at all. You can't declare a static interface at all in C#, nor can you declare static members within an interface.

Why interface does not contain static members?

Polymorphism works through instances - whereas static members explicitly don't use instances. that's the reason interfaces don't have static methods.

Can a interface have non static variable?

No you cannot have non-static variables in an interface. By default, All the members (methods and fields) of an interface are public. All the methods in an interface are public and abstract (except static and default).


2 Answers

No, an interface in C# can't declare fields at all. You can't declare a static interface at all in C#, nor can you declare static members within an interface.

As per section 11.2 of the C# specification:

An interface declaration may declare zero or more members. The members of an interface must be methods, properties, events, or indexers. An interface cannot contain constants, fields, operators, instance constructors, destructors, or types, nor can an interface contain static members of any kind.

All interface members implicitly have public access. It is a compile-time error for interface member declarations to include any modifiers. In particular, interfaces members cannot be declared with the modifiers abstract, public, protected, internal, private, virtual, override, or static.

like image 156
Jon Skeet Avatar answered Sep 22 '22 06:09

Jon Skeet


An interface is a contract, ie a description of the public instance methods and properties that any implementing class must provide.

Interfaces cannot specify any static methods or properties. They cannot specify internal, protected or private methods or properties. Nor can they specify fields.

like image 44
David Arno Avatar answered Sep 25 '22 06:09

David Arno