@property and interfaces

Steven Schveighoffer schveiguy at yahoo.com
Tue Jun 29 05:08:59 PDT 2010


On Tue, 29 Jun 2010 06:58:54 -0400, BLS <windevguy at hotmail.de> wrote:

> On 29/06/2010 12:32, Jonathan M Davis wrote:
>> So, there certainly won't be any restriction on
>> having a getter or setter in a class if an interface it implements  
>> declared only
>> one. It's just that you'll only be able to use the one that's part of  
>> the
>> interface if you're using a reference of the interface type rather than  
>> the
>> implementing class.
>
> Hi Jonathan,
> interesting : this snippet compiles.
>
> interface IBindingList {
> 		
> 	@property bool AllowEdit();
>
>
> class A : IBindingList {
> 	private bool _allowEdit;
>
> 	@property {
> 		bool AllowEdit() { return _allowEdit;	}
> 		bool AllowEdit(bool enable) { return _allowEdit = enable; }
> 	}	
> }
>
> But this one NOT.
>
> interface IBindingList {
> 		
> 	@property bool AllowEdit();
> 	@property bool AllowEdit(bool enable);
> }
> class A : IBindingList {
> 	private bool _allowEdit;
>
> 	@property {
> 		bool AllowEdit() { return _allowEdit;	}
> 	}	
> }
> IMO this is bad design.

Classes are always able to add functionality beyond what the interface  
declares.  IMO, it's actually bad design of C# not to allow you to declare  
setters even if the interface declares only a getter.

If you access an A instance through the IBindingList, you only have access  
to a getter, so it is properly implementing the interface.  I don't see  
why adding a setter detracts from it.

What if you had this in C#?

interface I1
{
    int x { get; }
}

interface I2
{
    int x {get; set;}
}

class C : I1, I2 // my C# is a bit rusty, I can't remember if this is how  
you implement interfaces
{
   ???
}

Besides, try to do this in C#:

@property int value() {return _x;}
@property int value(int x) { return _x = x;}
@property int value(string s) { return _x = to!int(s);}

:)  D's properties are so much better...

-Steve


More information about the Digitalmars-d-learn mailing list