!Dan Vallejo's WebLog!

Visual Studio .NET Developer

Implementing Properties on an Interface

When you implement an interface that has a property. You would think that you wouldn't be able to add additional accessors. Given the IDisplay interface below then class should only be allowed to implement the set accessor. But in reality since properties really resolve down to just functions, all you are really doing is just adding another function to your class.

So you can actually implement the interface property with both the get and set accessor even though the propery is only supposed to have the set accessor.

interface IDisplay
{
    string Message
    {
        set;
    }
}
   
class Shape : IDisplay
{
    public string Message
    {
        get // not part of the interface
        {
            return msg;
        }
        set
        {
            msg = value;
        }
    }
}

Note: That this ONLY works when you use public interface implementation if you switch this to explicit interface implementation then you get a compiler error.

class Shape : IDisplay
{
    string IDisplay.Message
    {
        get // syntax error
        {
            return msg;
        }
        set
        {
            msg = value;
        }
    }
}

Published Saturday, May 22, 2004 2:06 PM by DanVallejo
Filed under:

Comments

 

AT said:

Short answer ;o) Compiled and working.

<pre>
interface IDisplay
{
string Message
{
set;
}
}

interface IEmail
{
string Message
{
set;
}
}

class ShapeMessage: IDisplay, IEmail
{
string msg;

public string Message
{
get
{
return msg;
}
}

string IDisplay.Message
{
set
{
msg = "IDisplay: "+value;
}
}

string IEmail.Message
{
set
{
msg = "IEmail: " + value;
}
}
}
</pre>

Code:

<pre>
ShapeMessage sm = new ShapeMessage();
(sm as IDisplay).Message = "Message";
Console.WriteLine("{0}", sm.Message);
(sm as IEmail).Message = "Message";
Console.WriteLine("{0}", sm.Message);
</pre>

Result:

<pre>
IDisplay: Message
IEmail: Message
</pre>
May 22, 2004 4:11 PM
 

Dan Vallejo said:

Note quite what I was talking about (but a very interesting problem). You've got explicit interface implementation for Message which is different from the public Message property. These are two very different properties now. Either way very cool.
Thanks.
May 23, 2004 6:32 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker