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
-
Economics & Finance
How to declare member function in C# interface?
To declare member functions in C# interfaces, you define method signatures without implementations. The implementing class must provide the actual method bodies using the public access modifier.
Syntax
Following is the syntax for declaring member functions in an interface −
public interface InterfaceName {
ReturnType MethodName(parameters);
void AnotherMethod();
}
The implementing class must provide implementations for all interface methods −
public class ClassName : InterfaceName {
public ReturnType MethodName(parameters) {
// implementation
}
public void AnotherMethod() {
// implementation
}
}
Key Rules
Interface methods are implicitly public and abstract − no access modifiers or method bodies in the interface.
Implementing classes must use
publicaccess modifier for interface methods.All interface methods must be implemented in the class, or the class must be declared
abstract.
Example
using System;
public interface ICalculator {
void DisplayInfo();
double Add(double a, double b);
double Multiply(double x, double y);
}
public class BasicCalculator : ICalculator {
public void DisplayInfo() {
Console.WriteLine("Basic Calculator");
}
public double Add(double a, double b) {
return a + b;
}
public double Multiply(double x, double y) {
return x * y;
}
}
public class Program {
public static void Main() {
ICalculator calc = new BasicCalculator();
calc.DisplayInfo();
Console.WriteLine("5 + 3 = " + calc.Add(5, 3));
Console.WriteLine("4 * 6 = " + calc.Multiply(4, 6));
}
}
The output of the above code is −
Basic Calculator 5 + 3 = 8 4 * 6 = 24
Multiple Interface Implementation
A class can implement multiple interfaces by separating them with commas −
using System;
public interface IDrawable {
void Draw();
}
public interface IMovable {
void Move(int x, int y);
}
public class Shape : IDrawable, IMovable {
private int posX, posY;
public void Draw() {
Console.WriteLine("Drawing shape at (" + posX + ", " + posY + ")");
}
public void Move(int x, int y) {
posX = x;
posY = y;
Console.WriteLine("Moved to (" + x + ", " + y + ")");
}
}
public class Program {
public static void Main() {
Shape shape = new Shape();
shape.Move(10, 20);
shape.Draw();
}
}
The output of the above code is −
Moved to (10, 20) Drawing shape at (10, 20)
Conclusion
Interface member functions in C# are declared as method signatures without implementations. The implementing class must provide public implementations for all interface methods. Interfaces enable multiple inheritance and define contracts that classes must follow.
