0

Looking at a WCF tutorial, there is a class with private variable declarations and public getters and setters for those declarations. Is it possible to have this same combination of modifiers (i.e. private vars with a publicly exposed accessors) using the shortand get and set declarations?

For example:

public class MyClass{
  private int someNumber;

  public int someNumber {
    get {return someNumber;}
    set {someNumber = value;}
  }
}

This question here suggests you can mix modifiers like this:

public class MyClass{
  private int someNumber {public get; public set;};
}

Is that correct? (Also, in this specific example I can't see the point of marking int someNumber as a private variable. Am I right that this would be pointless?)

Community
  • 1
  • 1
Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • 1
    Why not simply try it out? – MakePeaceGreatAgain Jan 26 '17 at 11:40
  • 3
    You can only restrict access compared to the property access modifier when applying an access modifier to an individual accessor. In other words, you can make the property public and an accessor private. However, what exactly would be the point of declaring it the way you did, with a property modifier and modifiers on **both** accessors? In effect your property would be public (and that's why the compiler prohibits you from applying an access modifier to both, it will only allow it to **either** the getter or the setter). – Lasse V. Karlsen Jan 26 '17 at 11:40

2 Answers2

3

You can but the inner property methods must be more restrictive than the outside property itself.

public int someNumber { get; private set; }

This is how you make an externally read-only property.

This doesn't work (the compiler will complain) and does not make a lot of sense:

private int someNumber { get; public set; }
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

You can have different visibility level but you should always go from the more restrictive to the more open.

For instance you can have :

public string MyProperty { get; internal set; }

But you can't have :

private string MyProperty { public get; set; }

As the public access modifier of the getter is more visible than the private access modifier on the property.

Emmanuel Istace
  • 1,209
  • 2
  • 14
  • 32