Why use public variables?

2019-03-30 17:37发布

Variables, methods and classes can receive various security levels. From my C# experience, there is:

public
internal
protected
protected internal
private

Now, I understand the use of making methods and classes private, or internal or protected, but what about variables? Even if I make a variable private, I can use a Property to call it from a different class.

I've always been thought that Properties are best-practice. So if I can use that, I don't need to call variables directly via an Instance.

Is there any reason not to make a variable private?

EDIT: I see some people talking about Properties as if they are nothing more than Glorified public variables

Quick reminder: public variables return just their value. With properties, you can do more. For instance:

public int AmountOfBooks{
  get {
    //code to check certain conditions
    //maybe trigger an event while we're at it.
    //and a few conditionals.
    return this.amountOfBooks;
  }

  set {
    //a few conditionals
    //maybe trigger an event
    this.amountOfBooks = value;
    //and I can do even more... I think, never tried this.
  }
}

Those of you who've read my profile know I'm a student. Using properties as "glorified public variables" is something I see a lot of fellow students do. The most common response when telling them they can do this is: "Is that allowed?"

8条回答
萌系小妹纸
2楼-- · 2019-03-30 18:12

Off the top of my head, I can think of two places where I would use public fields

  1. to publish constant or read-only values for consumers of an assembly
  2. where I am forced to by parts of the infrastructure (e.g in Workflow Foundation)
查看更多
霸刀☆藐视天下
3楼-- · 2019-03-30 18:18

for example, if you had a class with attribute id_code.

if the attribute is public I can set this variable with any type of value.

if you delcare this id_code private and you make a method for set it, you can make a rules about the format of id_code. And so the method:

public setIdCode(String id) {
    my_attribute_id_code = "000"+id;
}

this is a first simple example.

查看更多
登录 后发表回答