I do understand how writing an interface works in C#, as for example described here: codeguru explanation
interface IIntelligence
{
bool intelligent_behavior();
}
class Human: IIntelligence
{
public Human()
{
//.............
}
/// Interface method definition in the class that implements it
public bool intelligent_behavior()
{
Console.WriteLine("........");
return true
}
}
I am however confused about the following process of interface casting:
Human human = new Human();
// The human object is casted to the interface type
IIntelligence humanIQ = (IIntelligence)human;
humanIQ.intelligent_behavior();
What is the sense of having a class (Human in this case) implement an interface, and then casting its instance human back to the interface? The question is not how it works, but why it is done.
.net offers two types of interface implementations implicit implementation and explicit implementation.
When you are using implicit implementation , it will become part of the type interface itself for example if you have a IPerson interface like this :
public interface IPerson
{
string Name{get;}
}
and you implement it as follows :
public class Person:IPerson
{
public string Name{get; ....}
}
you can access it like this (implicitly):
aPerson.Name;
but if you implement it like this (explicitly) :
public class Person:IPerson
{
string IPerson.Name{get; ....} // notice that there's no need to include access modifier.
}
Then it can only be accessed using IPerson interface:
((IPerson)aPerson).Name;
UPDATE:
Actually ,explicit interface implementation allow us to implement different interfaces with members that have same name.(as shown in this Tutorial)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With