Why we need Properties in C#

前端 未结 8 1195
萌比男神i
萌比男神i 2020-12-01 09:31

Can you tell me what is the exact usage of properties in C# i mean practical explanation

in our project we are using properties like

/// 

        
8条回答
  •  爱一瞬间的悲伤
    2020-12-01 10:23

    Design Time Benefits

    Properties makes visual designing easy, you have Most Famous Property Browser of Visual Studio to allow you to change properties of object.

    Properties also provide additional metadata of validation, visual appearance inside Property Browser, like drop down, range, color picker etc.

    Seperate Data and Actions

    They truely represent difference between "Data" of object and "Actions" (Methods) of object.

    When we look at class, if we have 50 methods to look at, not everyone will always use correct naming of functions, that will make things difficult to understand later on. I always tell the programmers that whenever you program, write the code in such a way that after 5 years, if someone else looks at the code, he should understand the code.

    Using method names of data access and some actions create confusion in long run... like in case of Stack, Push/Pop are actions but "Size" or "Count" is data.

    Creating property of "Count" simply distinguishes its purpose as data instead of action.

    Databinding

    As mentioned by others, properties offer advanced level of databinding like two way binding etc.

    Access Restrictions

    You can have readonly properties and additional accessors as mentioned by others.

    Reflection

    Its little easy to work with properties in case of writing generic code based on reflection.

    Different Storage Implementation

    Public variables store data only as members, where else properties provide various ways to store data in different forms like internaly they can be stored as hashtable (as they are done in dependency objects in WPF). They can be cached. They cab be relayed further to some other child entities or foriegn entities. However implementation is hidden for callers.

    Validation

    Setting property may require certain validation, and validation code in "Set" part of code can easily help you validate the input and report errors accordingly.

    Notifications

    Set part of method can raise notification events such as INotifyPropertyChanged.PropertyChanged which other objects can listen for and update the display value. This is important part of advanced data binding.

    In short, its a new "Standard" of data storage that has advanced facilities then just mere storing the data in the members of class. By avoiding properties typically you can perform all functions, but since implementation may differ from person to person, its a standard which helps everyone to define/access/validate/notify the data storage in one single form called "Properties"

提交回复
热议问题