Distinction between attributes and member variables in C

  • 2020-06-03 08:11:18
  • OfStack

Sometimes it is not clear whether to use member variables or attributes.
Such as:
Member variables
public string Name;

Or use attributes
private string name
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}

Properties are similar to member variables in that they provide data storage, but they are far more powerful than member variables. Properties are accessed by special methods (Get and Set accessors). Get and Set accessors allow you to validate property values, perform other code, or perform other tasks after setting or retrieving properties

For example,

Let me write the member variable like this
public readonly string Name;
It could still be read-only

private string name
public string Name
{
get
{
return name;
}

}

Object-oriented programming is to abstract and encapsulate; In a class, the variables defined are directly relative to the class itself, and we call them fields. It can be public,private, etc. An attribute is a property of a class that is externally visible, and it is a property that the class presents to an external consumer. We mentioned earlier that the domain can be public, but declaring the domain as public would be detrimental to class encapsulation, since external consumers can modify the class directly. So we can use the properties, we just expose their properties, and how we assign them (set) and how we value them (get) is encapsulated and not visible outside of the class. You can only use it for external consumers, you can't control it, and it's up to the class itself to control the operation. Do you understand?


Related articles: