Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is interface casting for in C#?

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.

like image 621
user748261 Avatar asked May 11 '11 08:05

user748261


1 Answers

.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)

like image 160
Beatles1692 Avatar answered Sep 20 '22 21:09

Beatles1692