Introduction
In this article, we will learn about properties in C#, different types of properties, how to define and use them, and some best practices when working with properties in C#, properties in C# are a way to encapsulate data and provide controlled access to it. They allow you to define a property as a member of a class, structure, or interface and provide a way to access the underlying data without exposing the data members directly.
What are Properties in C#?
A property in C# is a member of a class, structure, or interface that provides a way to access the underlying data. It is defined using the keyword “property” followed by the data type and the name of the property and a set of curly braces { } that contain a get accessor and a set accessor, which determine how the property can be accessed and modified. The get accessor is used to retrieve the value of the property, and the set accessor is used to set the value of the property.
Types of Properties in C#
C# has two types of properties.
- Read-only properties: A read-only property has a get accessor but not a set accessor, which means that the property can only be read and not modified.
- Read-write properties: A read-write property has both a get and a set accessor, which means that the property can be read and modified.
How do we define a read-only property in C#?
There are a few ways to define a read-only property in C#.
- Using the auto-implemented feature with a private setter: The compiler will automatically create a private field to store the value. The set accessor is marked as private, so it is only accessible within the class and cannot be used to modify the value.
public int MyProperty { get; private set; }
- Using the get accessor only: In this, get the accessor to return the value of the private field myField. In this case, there is no set accessor, so the property is read-only.
private int myField;
public int MyProperty { get { return myField; } }
- Using the Expression bodied members feature: This feature is available from C# 6.0 onwards, it allows you to access the value of the private field myField without having to define the get accessor explicitly.
private int myField;
public int MyProperty => myField;
- Using ReadOnly attribute: It is a way to set a property as read-only. It is not a built-in feature of C#, but it can be implemented by using a namespace that is “System.ComponentModel”
[ReadOnly(true)]
public int MyProperty { get; set; }
How do you define a read-write property in C#?
There are a few ways to define a read-write property in C#.
- Using the auto-implemented feature: The compiler will automatically create a private field to store the value. Both the get and set accessors are public, so the property is read-write.
public int MyProperty { get; set; }
- Using the get and set accessors: In this, get and set accessors allow reading and writing the value of the private field myField. The get accessor returns the value of the field, and the set accessor assigns a new value to the field.
private int myField;
public int MyProperty { get { return myField; } set { myField = value; } }
- Using the Expression bodied members feature: This feature is& available from C# 6.0 onwards, it allows you to access the value of the private field myField without having to define the get and set accessor explicitly.
private int _myField;
public int MyProperty { get => _myField; set => _myField = value; }
- Using get and private setter accessor: You can also use a private setter and make it read-only outside the class but writable inside the class. It can only be used inside the class to change the value of the property, but it can be read from outside the class.
private int _myField;
public int MyProperty { get => _myField; private set => _myField = value; }
How to Use Properties in C#?
Here I have an example in which we will learn& how properties can be used to provide a simple and easy way to access and modify the data of a class.
//Author: Deepak Tewatia
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person p= new Person();
p.FirstName = "Deepak";
p.LastName = "Tewatia";
Console.WriteLine("My Full Name is : " + p.FirstName + " " + p.LastName);
}
}
in the above example, the Person class has two public properties, FirstName and LastName, which are both defined using the shorthand syntax { get; set; }. This automatically generates a private field for each property and creates get and set accessors for each property.
Now, in the Main method of the Program class, an instance of the Person class is created and assigned to the variable person. The FirstName and LastName properties are then set to “Deepak” and “Tewatia” respectively.
This example shows how properties can be used to provide a simple and easy way to access and modify the data of a class while also providing a way to control access to the data and add additional behavior. The output of the above code snippet is shown in below Figure-1.
What are Properties Access Modifiers in C#?
Properties Access Modifiers are keywords used to specify the accessibility of a property. The following are the access modifiers for properties in C#.
- Public: The property is accessible from any code.
- Private: The property is only accessible within the same class.
- Protected: The property is accessible within the same class and any derived classes.
- Internal: The property is accessible within the same assembly.
- Protected internal: The property is accessible within the same assembly and any derived classes.
- Private protected: The property is accessible within the same class and any derived classes within the same assembly.
What is Static Property in C#?
A static property is a property that belongs to a class, rather than an instance of the class. This means that it can be accessed directly using the class name, rather than creating an instance of the class. Static properties are defined with the static keyword and do not require an instance of the class to be created to access them.
The main advantage of using static properties is that they can be accessed from anywhere in the program without having to create an instance of the class. This can help to improve the performance of a program, as creating new instances of a class can be resource-intensive. Additionally, since the property belongs to the class, it can only have one value across all instances, which can be useful in cases where you want to share a single value between different instances of a class.
It is important to note that static properties are not associated with any particular instance of a class, so they cannot be used to refer to the state of a specific object. Instead, they are used to store values that are common to all instances of the class.
Here is an example of a static property.
class MyClass
{
public static int MyProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyClass.MyProperty = 10; //setting the value of MyProperty
Console.WriteLine("The value of MyProperty is: " + MyClass.MyProperty);
}
}
The output of the above code snippet is given in below Figure-2.
What is Polymorphism in C#?
Polymorphism in C# is the ability for a single object to be treated as an instance of multiple different types. This is achieved through inheritance, interfaces and/or overriding methods. This is a fundamental concept in OOPs, as it enables code to be written in a more flexible and reusable. If you're unfamiliar with OOPs, please read Object Oriented Programming In C# (c-sharpcorner.com).
Here is an example of polymorphism.
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
class Square : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a square");
}
}
class Program
{
static void Main(string[] args)
{
Shape shape = new Circle();
shape.Draw(); // Output: "Drawing a circle"
shape = new Square();
shape.Draw(); // Output: "Drawing a square"
}
}
In the above code snippet, the Shape class has a Draw method that is overridden by the Circle and Square classes. The Main method creates a Shape object, assigns it to a Circle object, and calls the Draw method. The output is “Drawing a circle”. Then it assigns the same shape object to a Square object, calls the Draw method again, and the output is “Drawing a square”, as shown in below Figure-3.
What are the best practices for working with Properties in C#?
- Use properties instead of public fields: Using properties instead of public fields is a better way to access and control the data in your code, and it allows for added behavior like validation or logging.
- Keep properties private when possible: Keeping properties private and using getters and setters helps to keep the inner workings of a class hidden and protected, making it harder for the data to be accidentally changed.
- Use shorthand syntax: The shorthand syntax { get; set; } can be used to automatically generate a private field and create get and set accessors. This is a convenient way to create simple properties.
- Use explicit implementations for interface properties: When implementing an interface property, it is considered best practice to use an explicit implementation instead of an implicit implementation.
- Use read-only properties when appropriate: If a property should only be able to be read and not modified, consider using a read-only property.
- Use properties for computed values: Properties can be used to return computed values, such as the total cost of an order, instead of storing the value in a field.
- Use events with properties: Properties can be used with events to notify other objects when a property value has been changed.
- Avoid using properties for performance-critical code: Properties are useful for encapsulation and adding behavior, but they can introduce overhead and should not be used for performance-critical code.
Conclusion
Here, we have learned about properties in C#, Types of Properties, How to define a read-only property, How to define a read-write property, How to Use Properties, What are Properties Access Modifiers.
If you have any queries or suggestions, please leave your questions and thoughts in the comment section below. Follow C# Corner to learn more new and amazing things about .NET or to explore more technologies.
Thanks for reading, and I hope you like it.