C# PROPERTIES
Before we discuss about properties we should have a basic understanding of Encapsulation.
Encapsulation means to hide sensitive data from users.None can show our private and sensitive data with this.
To achieve Encapsulation we have to declare our fields with private keyword.
Next we have to provide public get and set properties to access our private fields.
For understanding this process here a picture is given.
Here we declare our fields with private keyword so it can be
access in same class,if we want to access this field from outside the class we can use public properties get set as given in picture.
Properties can have access modifiers like public, private, protected, or internal, controlling the visibility of the property to other classes.
Properties often use backing fields (private fields within the class) to store their values. The getter and setter methods access these backing fields.
Properties can include logic for validating the value being set, ensuring that only valid data is stored.
AUTOMATIC PROPERTIES(SHORT HAND)
C# also provide short hand property where we not have to define the field for the property and you only have to write get and set inside the property.
Here is a picture of short hand property for concise understanding.
Here we can see above both picture are presenting same result but with short hand property how much our code is become reduced.
Short hand property we can use if we don't want to write logic in our get and set property for our program.
Properties can be used to define events, enabling classes to notify other classes when their properties change.
Properties can also be used to create indexers, allowing objects to be indexed in a similar way to arrays.
In summary we saw about properties,implementation of properties and familiar with get and set at last we saw short hand properties.
In C#, properties are a fundamental concept used to encapsulate fields within a class and provide controlled access to them.
Take the first step towards data-led growth by partnering with MSA Infotech. Whether you seek tailored solutions or expert consultation, we are here to help you harness the power of data for your business. Contact us today and let’s embark on this transformative data adventure together. Get a free consultation today!
We utilize data to transform ourselves, our clients, and the world.
Partnership with leading data platforms and certified talents