Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting properties with accessibility modifier in C#

I tried to inherit interface, and make some of the automatically generated set property as 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 an error 'MyClass.C' does not implement interface member 'MyClass.A.X.set'. 'MyClass.C.X.set' is not public..

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

Is this accessibility modifier not allowed in C#?

like image 453
prosseek Avatar asked Sep 24 '11 01:09

prosseek


2 Answers

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

If your interface only requires that a property should be retrievable, you define it as:

public interface A 
{
    int X {get;}  // Leave off set entirely
}
like image 62
Reed Copsey Avatar answered Oct 08 '22 17:10

Reed Copsey


The declaration of an interface defines the public set of members that the implementing type must have. So, if C implements A, it must have a public member for each member defined by the interface.

A defines that any implementing type must have a public property X with a public getter and a public setter. C does not meet this requirement.

like image 43
dtb Avatar answered Oct 08 '22 18:10

dtb