Google
 

Tuesday, September 11, 2007

Differences between implicit and explicit implement interface in .Net

1.To explicit implement interface, the scope directive can't be used.

     public class A : ITrace
    {       
        // implicit implement interface ITrace
        
public  string TraceSelf()
        {
            
return "A";
        }
    }
    
public interface  ITrace
    {
        
string TraceSelf();            
    }
    
public class B : ITrace
    {       
     // explicit implement the interface ITrace
        
string  ITrace.TraceSelf()
        {
            
return "B" ;
        }
    }
   

2.To retrieve the explicit implemented members, the only way is to use interface. The  explicit implemented member is default private to the class object.


    [TestFixture]
    
public class TestClass1
    {
        [Test]
        
public void TestMethod()
        {
            A a 
= new A();
            // Call the implicit implemented method
            a.TraceSelf();
        }
        [Test]
        
public  void TestMethod1()
        {            
            B b 
=  new B();
            
// b.TraceSelf(); can't call the implemented method this way
            ((ITrace)b).TraceSelf();
        }
    }


--
Happy day, happy life!

No comments: