Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it not breaking design principle of interface in c#?

Tags:

c#

interface

When I googled to find the related topics about interface, I found this from MSDN website:

For example, an interface might declare a property that has a get accessor. The class that implements the interface can declare the same property with both a get and set accessor. from MSDN

Now I have a doubt. When we specifically mentioned that the property should be read only(only 'get' accessor in the interface) why is it allowed to implement 'set' accessor also?

like image 893
Syed Avatar asked Nov 30 '22 06:11

Syed


2 Answers

Now I have a doubt. When we specifically mentioned that the property should be read only(only 'get' accessor in the interface) why is it allowed to implement 'set' accessor also?

There's a difference - when you use an interface, you're not "specifying that the property should be read only", but rather specifying that the contract defines a "readable property" of that specific name and type. Basically, the interface defines the minimum requirements for a contract, not the absolute requirements.

If you cast the object to the specific interface, the property setter will not be available. It's really no different than having extra properties or methods on the object that aren't available via the interface.

like image 113
Reed Copsey Avatar answered Dec 04 '22 14:12

Reed Copsey


You can't access the set property from a interface reference, so it doesn't matter if it's implemented or not when revealing the interface to the public.

Of course it's sometimes necessary to implement a set accessor on class side, i.e. when working with a class which allows access of classes which are in the same assembly.

like image 34
Felix K. Avatar answered Dec 04 '22 15:12

Felix K.