-3

Why does this code not work?

class Test
{
    int Abc { private set; get; }
}

What is the default access modifier for properties?

David Hoerster
  • 28,421
  • 8
  • 67
  • 102
Never
  • 335
  • 2
  • 7
  • 23
  • possible duplicate of [C# - Property must be more restrictive?](http://stackoverflow.com/questions/6886514/c-sharp-property-must-be-more-restrictive) – Saeed Amiri Jan 15 '12 at 15:19
  • @Saeed while similar I don't think that one's a dup. – kenny Jan 15 '12 at 15:49
  • @kenny, In the question I mentioned it, OP described the problem of this problem (and implicitly how to solve it). In fact simple search in SO helps the current OP to solve his/her problem. – Saeed Amiri Jan 15 '12 at 16:53

3 Answers3

4

The Abc property must be public, protected or internal:

public int Abc { get; private set; }

In your case the property is private (because you haven't specified an access modifier) so it's already a private set. You cannot modify its value outside of the current class so it doesn't really make sense to declare a private setter in this case.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • @Colder, you can. and it is already private. So it is meaningless to define a private setter for a private property. Nothing outside of the current class can modify its value anyway. It also cannot get its value because the property is private. In this case you don't use a property. You use a field: `private int Abc;`. – Darin Dimitrov Jan 15 '12 at 15:17
3

Default access modifier for properties is private, as for any other member of a class. If you wish to make the setter less accessible you would need to make the property more accessible first and then put restriction on the setter.

class Test
{
    public int Abc1 { private set; get; }
    protected  int Abc2 { private set; get; }
    internal int Abc3 { private set; get; }
    protected internal int Abc4 { private set; get; }
}
oleksii
  • 35,458
  • 16
  • 93
  • 163
3

The default accessibility of all class members (including properties) is private; see Accessibility Levels. The private before your set is redundant, thus the error. Your code would be semantically equivalent to the following:

class Test
{
    int Abc { get; set; }
}

You only need to specify a private access modifier for your set accessor when the property is more accessible; for example (a common scenario):

class Test
{
    public int Abc { get; private set; }
}
Douglas
  • 53,759
  • 13
  • 140
  • 188