Sunday, February 1, 2009

Difference Between Explicit And Implicit Interface Implementation

Interface can be implemented two ways. Explicitly or Implicitly.
For Example :
public interface IEmployee
{
         string FullName
         {
               get;
               set;
         }
}

Implicit implementation of Interface
public class ImplicitClass : IEmployee
{
     public string FullName
     {
           get ;
           set ; 
     }
}

Explicit implementation of Interface.
public class ExplicitClass : IEmployee
{
    string IEmployee.FullName
    {     
           get ;
           set ;  
    }
}
Here you can see that FullName property does not have access modifier.As this is explicit implementation so it does not allow access modifier.

Now we see what happen when try to create object of both of above class.

ImplicitClass cls = new ImplicitClass();
cls.FullName = “test”;
// Above code works fine

ExplicitClass cls1 = new ExplicitClass();
cls1.FullName = “test”; // error occur

As interface implement explicitly FullName property not available directly to cl1 object b’coz it become private to the Interface type.
img1
By reflection

ImplicitClass cls = new ImplicitClass();
PropertyInfo pinfo = cls.GetType().GetProperty("FullName");
if (pinfo != null)
    {
     pinfo.SetValue(cls, "test",null);
    }       

ExplicitClass cls1 = new ExplicitClass();
PropertyInfo pinfo1 = cls1.GetType().GetProperty("FullName");
            if (pinfo1 != null) // pinfo1 is null in this case.
            {
                pinfo1.SetValue(cls1, "test",null);
            }      

By reflection way also not able to set property as can no available propertyinfo.

Solution for this is , If interface implemented explicit way then cast to Interface type then set property.

ExplicitClass cls1 = new ExplicitClass();
IEmployee emp = cls1 as IEmployee;
emp.FullName = “test”;

if want to access with use of Reflection
ExplicitClass cls1 = new ExplicitClass();                        PropertyInfo pinfo1 = cls1.GetType().GetInterface("IEmployee").GetProperty("FullName");
if (pinfo1 != null)
{
   pinfo1.SetValue(cls1, "test",null);
}      

Note: only choose explicit interface if needed. One such case is if your class previously has property/Event/Method that Interface has also , than to avoid conflict must need of explicit interface implementation.

Please give you further suggestion about this article.

4 comments:

Anonymous said...

Thans for your article. keep posted

Thanks,

TechHowKnow

Anonymous said...

Super article.. Its simple and east to understand.. Good article.. beginner can understand easily..

Vaibhav Jain said...

Defining very nicely, as a software developer I appreciate this post.
iPhone Mobile Application

Anonymous said...

Good One.