Inheriting properties using an accessibility modifier in C #

I tried to inherit the interface and make part of the automatically generated set property private. This is an example.

public class MyClass { public interface A { int X {get; set;} } public interface B : A { int Y {get; set;} } public class C : A { public int X {get; private set;} } 

When I tried to compile it. I got the error 'MyClass.C' does not implement interface member 'MyClass.AXset'. 'MyClass.CXset' is not public. 'MyClass.C' does not implement interface member 'MyClass.AXset'. 'MyClass.CXset' is not public. .

I tried with private set; in iterface A , but got this error again: 'MyClass.AXset': accessibility modifiers may not be used on accessors in an interface .

Is this accessibility modifier allowed in C #?

+7
source share
5 answers

I tried with a private set; in iterface A, but I got this error again

If your interface only requires that the property needs to be restored, you define it as:

 public interface A { int X {get;} // Leave off set entirely } 
+21
source

An interface declaration defines an open set of members that must have an implementation type. So, if C implements A , it must have an open member for each member defined by the interface.

A determines that any type of implementation must have public property X with a public receiver and a public network device. C does not meet this requirement.

+1
source

You can imagine the interface as the minimum functionality that your class should implement. If the interface indicates that the property provides a get and set clause, then you must implement the public get and set clause in your class, since only public methods and properties can implicitly implement interfaces.

You can simply leave the set keyword in the definition of an interface property if you do not want to publish the public mutator. You can then make the implementation mutator public or private.

0
source

No, it is forbidden. Remember that code that uses an instance of class C should be able to treat it as interface A , which means that the contract is the public recipient and installer for the X property.

This applies to class inheritance, as well as interface inheritance - you must follow the contract of the type from which you derived.

If the purpose of the code is that property X should not have a public setter, then the interface should only be defined using { get; } { get; }

0
source

I believe that interface members should be public if the interface itself is public. Because of this, your property implementation is erroneous.

0
source

All Articles