In this post, we will see the difference between explicit and implicit implementation of interface in C#.
In C#, when implementing an interface, you have two options: explicit implementation and implicit implementation. These approaches are used to define how a class implements the members (methods, properties, events) of an interface.
1. Implicit Implementation:
In an implicit implementation, you define the members of the interface using the standard access modifiers (e.g., public, private, protected) directly in the class that implements the interface. This means that the members are accessible using the class instance without casting it to the interface type. Here's an example:
interface IExampleInterface
{
void SomeMethod();
}
class ExampleClass : IExampleInterface
{
public void SomeMethod()
{
Console.WriteLine("Implemented SomeMethod.");
}
}
// Usage
ExampleClass example = new ExampleClass();
example.SomeMethod(); // Accessible directly through the class instance
2. Explicit Implementation:
In an explicit implementation, you specify the interface name before the member to disambiguate it from any other members with the same name. This is typically used when a class implements multiple interfaces and those interfaces have members with the same names. Explicitly implemented members are only accessible through an instance of the interface or by explicitly casting the class instance to the interface type. Here's an example:
interface IExampleInterface
{
void SomeMethod();
}
interface IExampleAnotherInterface
{
void SomeMethod();
}
class ExampleClass : IExampleInterface
{
void IExampleInterface.SomeMethod() // Explicit implementation
{
Console.WriteLine("Implemented SomeMethod.");
}
}
// Usage
ExampleClass example = new ExampleClass();
((IExampleInterface)example).SomeMethod(); // Accessible through interface or by casting
In this example, SomeMethod is explicitly implemented for the IExampleInterface, so you must use an interface instance or an explicit cast to access it.
In summary, implicit implementation is straightforward and allows direct access to the interface members through the class instance. Explicit implementation is used when there is a need to disambiguate members with the same name from different interfaces or to provide a specific implementation for an interface when accessed through that interface.
Points to Remember
- In case of implicit implementation of interface, the members of interface are accessed by the instance of the class which implements the interface.
- In case of explicit implementation of interface, the members of interface cannot be accessed directly by the instance of the class which implements the interface. We can access the members of the interface by typecasting the instance of implementing class into the interface type.
No comments:
Post a Comment