Wednesday, March 24, 2010

Hiding Interface Members

We can also hide base class members on interfaces. Suppose that we have two interfaces: IBase and IDerived. As the name indicates, IDerived is derived from IBase. The following is a declaration of a property M1 in the interface IBase.
interface IBase
{
    int M1 {get; set; }
}
In the same program, we can declare a method with the same name, M1 on the interface IDerived:
interface IDerived: IBase
{
    new int M1();
}
With this declaration, the member M1 on the derived interface hides the member M1 on the base interface. In this case, it is necessary to use explicit interface implementation in any class that implements these interfaces:
class MyClass: IDerived
{
    private int m1;
    //Explicit implementation of the property M1:
    int IBase.M1
    {
        get { return m1; }
        set { m1 = value; }
    }
    // Explicit implementation of the method M1:
    void IDerived.M1() { }
}
It is also possible to implement the property explicitly and the method normally, as shown in this example:
class MyClass: IDerived
{
    private int m1;
    //Explicit implementation of the property:
    int IBase.M1
    {
        get { return m1; }
        set { m1 = value; }
    }
    // Normal implementation of the method:
    public void M1()
    {
    }
}
A third possibility is to implement the method explicitly and the property normally, as shown below:
class MyClass : IDerived
{
    private int m1;
    //Normal implementation of the property:
    public int M1
    {
        get { return m1; }
        set { m1 = value; }
    }
    //Explicit implementation of the method:
    void IDerived.M1() { }
}
In the following example, one of the explicit alternative implementations of method and property is demonstrated.
//Example 8-6.cs
//Hiding interface members
using System;
interface IBase
{
    int M1 { set;  get; }
}
interface  IDerived: IBase
{
    //Declare a method that hides the property
    // On the IBase interface:
    new void M1();
}
class MyClass: IDerived
{
    private int x;
    //Explicit implementation of the property:
    int IBase.M1
    {
        get { return x; }
        set { x = value; }
    }
    //Explicit implementation of the method:
    void IDerived.M1()
    {
        Console.WriteLine(“Hi, I am the M1 method!”);
    }
}
class MainClass
{
    static void Main()
    {
        // Create a class object:
        MyClass mc = new MyClass();
        //Create an IDerived object:
        IDerived mi1 = (IDerived)mc;
        //Create an IBase object:
        IBase mi2 = (IBase)mc;
        //Use the property:
        mi2.M1 = 123;
        //Call the method:
        mi1.M1();
        //Display the property:
        Console.WriteLine(“I am the M1 property. My value is {0}.”, mi2.M1);
    }
}

No comments:

Post a Comment