Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Why cannot we specify access modifiers inside an interface in C#?
Interface methods are contract with the outside world which specifies that class implementing this interface does a certain set of things.
Interface members are always public because the purpose of an interface is to enable other types to access a class or struct.
Interfaces can have access specifiers like protected or internal etc. Thus limiting 'the outside world' to a subset of 'the whole outside world'.
Example
interface IInterface{
void Save();
}
class Program{
static void Main(){
Console.ReadLine();
}
}
The above example will compile properly without any errors
Prior to C# 8, interface members were public by default. In fact, if you put an access modifier on an interface member (including public), it would generate a compiler error.
interface IInterface{
Public void Save();
}
class Program{
static void Main(){
Console.ReadLine();
}
}
The above code throws compile time error in c# 7.0,but in c# 8.0 it compiles without any error
