How to define and use properties in C#?
In C#, properties are members of a class used to encapsulate fields, providing a way to read and write data. Here are the basic steps for defining and using properties.
Define Attributes
Declare properties in a class: Define properties using the get and set keywords, specifying the data type and name of the property.
public class MyClass
{
private int _myProperty;
public int MyProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
}
Auto properties: If a property does not require any additional logic processing, you can use auto properties to simplify the definition.
public class MyClass
{
public int MyProperty { get; set; }
}
utilize attributes
Set the attribute value: access the attribute by its name and assign a new value.
MyClass obj = new MyClass();
obj.MyProperty = 10;
Retrieve property value: Access the property by name and get its value.
int value = obj.MyProperty;
3. Access modifiers for properties allow control over access permissions using keywords like public or private, as well as using readonly to make properties read-only.
public class MyClass
{
public int PublicProperty { get; set; }
private int PrivateProperty { get; set; }
public int ReadOnlyProperty { get; } = 100;
}
4. Property initializer: allows initializing the value of a property directly when declaring it.
public class MyClass
{
public int InitializedProperty { get; set; } = 50;
}
Defining and using attributes helps to better manage a class’s data members, increasing the encapsulation and maintainability of the code.