How to make derived interface property read-only ?

O

Oleg Subachev

I have one interface "Intf1" with read-write property "Prop" (with "get" and
"set" accessors).

Then I declare derived interface "Intf2" with the same property "Prop"
declared as read-only (without "set" accessor).
Property "Prop" in derived interface "Intf2" is marked with "new" modifier.

Then I implement derived interface "Intf2" in class "Clss2" with read-only
property "Prop" (without "set" accessor).
Property "Prop" in class "Clss2" is marked with "new" modifier.

During compilation I get the following error:

*******************
Clss2 does not implement interface member 'Intf1.Prop.set'
*******************

but property "Prop" is declared in interface "Intf2" and is read-only.

What's wrong ?


Oleg Subachev
 
B

Brian Gideon

Oleg,

Since Intf2 inherits Intf1 then Clss2 must implement everything in
Intf1 and Intf2. Now, because you've hidden a member declaration in
Intf2 using the 'new' keyword here's what you'll see happen.

Clss2 foo = new Clss2();
foo.Prop = 5; // ok

Intf1 foo = new Clss2();
foo.Prop = 5; // ok

Intf2 foo = new Clss2();
foo.Prop = 5; // compile error

Brian
 
J

Jon Skeet [C# MVP]

Oleg Subachev said:
I have one interface "Intf1" with read-write property "Prop" (with "get" and
"set" accessors).

Then I declare derived interface "Intf2" with the same property "Prop"
declared as read-only (without "set" accessor).
Property "Prop" in derived interface "Intf2" is marked with "new" modifier.

Then I implement derived interface "Intf2" in class "Clss2" with read-only
property "Prop" (without "set" accessor).
Property "Prop" in class "Clss2" is marked with "new" modifier.

During compilation I get the following error:

*******************
Clss2 does not implement interface member 'Intf1.Prop.set'
*******************

but property "Prop" is declared in interface "Intf2" and is read-only.

What's wrong ?

Well, you've declared that the class implements the first interface
(because the second interface derives from the first). The first
interface has a setter, therefore to implement the interface fully you
need a setter.

You can't use inheritance to "remove" members from an interface.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top