Reputation: 5326
It might be a silly question, I appreciate if someone can help me understand it.
Can an interface in C#
can have static variables?
If the interface itself need to be static to declare static variables inside?
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.
Upvotes: 8
Views: 15882
Reputation: 381
From C# 11 and .Net 7, you can add static members to interfaces; not only that, but you can make them abstract too
Upvotes: 3
Reputation: 43254
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.
Upvotes: 2
Reputation: 10476
1- No, because interface
is not a class
2- Consider an Abstract
class
3- Static Property
in an interface
is not defined nor is meaningful in C#
Upvotes: -3
Reputation: 1500515
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.
Upvotes: 19