简体   繁体   中英

C#: Can you mix function access modifiers when using getter/setter shortand?

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 (ie 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?)

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; }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM