C# implicit and explicit interfaces – In C#, an Interface can be implemented implicitly and explicitly. Here is the explanation of both implicit and explicit interface by example
When we implement an interface implicitly, we need to note two points
- Class will implement interface method with “public” modifier.
- Implemented interface method will be called on class object/interface reference
Implicit interface implementation example in C#
In below program example, class Maestro will implement the interface ICreditCard method using public modifier and implemented method will be call using class object or interface reference in Main().
C# Code Example
interface ICreditCard
{
void getCardInfo();
}
//Implicit implementation of Interface
//ICreditCard method
class Maestro : ICreditCard
{
//Implement interface method
public void getCardInfo()
{
Console.WriteLine("Implicit interface Implementation");
}
}
class Program
{
static void Main(string[] args)
{
//use class object to call implemented
//method
Maestro creditCard = new Maestro();
creditCard.getCardInfo();
//Using interface reference
ICreditCard iCreditCard = new Maestro();
iCreditCard.getCardInfo();
}
}
Output:
Implicit interface Implementation
Implicit interface Implementation
Explicit interface implementation example in C#
For explicit interface implementation, we also need to note two points
- Method implementation will contain interface name e.g.void ICreditCard.getCardInfo()in the class.
- It should not contain public modifier.
In explicit implementation class, method can only be called by assigning class object to interface reference and not on the class object.
C# Program Example
interface ICreditCard
{
void getCardInfo();
}
//Explicit implementation of Interface
//ICreditCard method preceding Interface name
//before method
class Platinum : ICreditCard
{
//Implement interface method
void ICreditCard.getCardInfo()
{
Console.WriteLine("Explicit interface Implementation");
}
}
//Test
class Program
{
static void Main(string[] args)
{
//Call possible only using interface reference
ICreditCard iCreditCard = new Platinum();
iCreditCard.getCardInfo();
}
}
Output:
Explicit interface Implementation
Implicit Interface and Explicit Interface – Important points:
- Explicit interface implemented method cannot be virtual or abstract while implicit interface in c# implementation in a class can be virtual and abstract.
- Interface method implemented implicitly in class should be public while for explicit implanted method should be private, because, explicit method in a class is implemented using interface name e.g. void ICreditCard.getCardInfo(), hence, there is no sense using public.