Why we need Properties in C#

前端 未结 8 1180
萌比男神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:12

    Here's a common pattern:

    class Foo {
    
        private Bar _bar;
    
        //here, Foo has a Bar object.  If that object has already been instantiated, return that value.  Otherwise, get it from the database.
        public Bar bar {
            set { _bar = value;}
            get {
                if (_bar == null) {
                    _bar = Bar.find_by_foo_name(this._name);
                }
                return _bar;
            }
        }
    }
    

    In short, this allows us to access the Bar object on our instance of Foo. This encapsulation means we don't have to worry about how Bar is retrieved, or if foo.bar has already been instantiated. We can just use the object and let the internals of the Foo class take care of it.

    0 讨论(0)
  • 2020-12-01 10:14

    As Justin noted, Encapsulation is one of the basic tenets of OOP. You would want to keep the internal representation of the data in your class hidden from outside and provide approved ways of viewing/manipulating it.

    C# properties are constructs that provide an easy way to do that. In your example, you aren't doing anything inside the get and set methods but in real life you may need to do certain things like

    • Store currency in 10th of cents as a long integer but return to the outside world as a string with 2 decimal spaces and a $ sign.
    • Restrict a certain property to be read-only (or even write-only: for ex:, a password validator/hash generator class).
    • Change the state of the object somehow when this value is set/get.

    In Java, you write getters and setters which are plain-old methods that return or accept a value respectively.

    0 讨论(0)
  • 2020-12-01 10:16

    Properties are used to restrict direct access to member variables of a class. Abstraction is maintained using properties. Whenever you want to instantiate an object and set data to it's member variables using property you can check some conditions whether the value will be set to the member variable or not. You can restrict read write to a property so that the value of member variable can be readonly, writeonly while accessing the object of that class.

    0 讨论(0)
  • 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"

    0 讨论(0)
  • 2020-12-01 10:27

    Lots of reasons:

    • Semantics. Properties separate the implementation of your type from the interface.
    • Binary Compatibility. If you ever need to change a property, you can do so without breaking binary compatibility for dependent code. With fields, you have to recompile everything even if the new implementation uses a property with the same name.
    • Databinding. You can't databind to a field.
    0 讨论(0)
  • 2020-12-01 10:28

    Short answer: Encapsulation

    Long answer: Properties are very versitile. It allows you to choose how you want to expose your data to outside objects. You can inject some amount of data validation when setting values. It also aliviates the headache of getX() and setX() methods seen in the likes of Java, etc.

    0 讨论(0)
提交回复
热议问题