07
DecProperties in C#: A Complete Guide
Properties in C#
Properties in C# act as a wrapper around a field. C# property is used to assign and read the value from a field by using set and get accessors. The code block for the get accessor is executed when the property is read, and the code block for the set accessor is executed when the property is assigned a new value. A C# property can be created for a public, private, protected, and internal field.
In this C# Tutorial, we will explore more about properties in C#; what is an accessor in C#?c# property with real-life examples, different types of properties, when to use properties with examples, the advantage of the property, what is a static property, abstract property, and many more. If you are a beginner in C# programming language, this C# Developer Roadmap article provides you with complete information.
What is Property in C#?
- C# Properties are used for a class to expose a public way of getting and setting values while hiding implementation or verification code.
- A get property accessor is used to return the C# property value, and a set property accessor is used to assign a new value.
- An initial C# property accessor is used to assign a new value only during object construction. These accessors can have different kinds of access levels.
- Properties in C# can be read-write(get, set), read-only(get), or write-only(set).
- Write-only properties in C# are used to restrict access to sensitive data.
- C# Properties do not denote storage locations, and you cannot pass a property as a reference or out parameter.
Example
Let's elaborate properties in C# Compiler with its example:
// C# program to illustrate the problems
// with public and private members
using System;
// public class
public class C1
{
// public data members
public int rn;
public string name;
// private field
// private int marks = 35;
}
// another public class
public class C2
{
// Main Method
public static void Main(string[] args)
{
// Creating object of C1 class
C1 obj = new C1();
// setting values to public
// data members of class C1
obj.rn = 10000;
obj.name = null;
// setting values to private
// data members of class C1
// obj.mark = 0;
// display result
Console.WriteLine("Name: {0} \nRoll No: {1}", obj.name, obj.rn);
}
}
Output
Name:
Roll No: 10000
Explanation
In the given code, the name variable is not initialized, so its default value is null. The rn variable is set to 10000. The private field marks are commented out and not used, so they do not affect the output.
Using Properties in C#
- Encapsulation: Properties enable data encapsulation by providing a controlled way to access class fields.
- Get and Set Methods: Properties in C# have to get and set methods, allowing read and write access to private fields while maintaining data integrity.
- Syntax: Declare properties using get and set accessors, defining the logic for retrieving and setting values.
- Access Modifiers: Properties in C# can have access modifiers like public, private, or protected, controlling their visibility.
- Data Validation: Properties in C# allow validation logic, ensuring only valid data is stored in class fields.
- Simplified Syntax: Properties simplify the syntax of accessing class members, enhancing code readability and maintainability.
What is Accessor in C#?
In C#, an accessor refers to a method or code block that is used to read or write the value of a private field in a class. Accessors are commonly used in properties to control the access to the underlying data, allowing encapsulation and ensuring data integrity in object-oriented programming.
There are two types of accessors in C# those are:
- Get Accessor
- Set Accessor
1. Get Accessor in C#
In C#, a get accessor retrieves the value of a private field in a class. It is part of a property declaration and returns the property value. Get accessors to allow controlled access to class properties, enabling encapsulation and data abstraction in object-oriented programming.
Example
class Scholar {
// Declare roll_no field
private int roll_no;
// Declare roll_no property
public int Roll_no
{
get
{
return roll_no;
}
}
}
Explanation
The given code defines a class Scholar with a private field roll_no and a public property Roll_no that allows access to the private field. Since the Roll_no property only has a get accessor, you can retrieve the value of the roll_no field but cannot set it from outside the class. There is no output in the code as it does not contain any logic to demonstrate the property usage.
2. Set Accessor in C#
In C#, a set accessor is a method used within a property to assign a value to that property. It allows you to control the behavior when a property's value is set. You define it using the "set" keyword followed by a code block that specifies how the value should be stored or processed.
Example
class Scholar {
// Declare roll_no field
private int roll_no;
// Declare roll_no property
public int Roll_no
{
get
{
return roll_no;
}
set
{
roll_no = value;
}
}
}
Explanation
This C# code defines a class Scholar with a private field roll_no and a public property Roll_no. The property has both get and set accessors, allowing external code to read and modify the private roll_no field. This encapsulation ensures controlled access to the roll_no data within the class.
Accessor Accessibility in C#
- Accessor modifiers are not permitted on an interface or an explicit interface member implementation.
- Only when a property possesses both set and get accessors can we employ accessor modifiers.
- The accessor modifier for an override property has to match the overriding accessor's accessor.
- The accessor modifier for an override property has to match the overriding accessor's accessor.
Different Types of Property
Properties can be divided into three categories that are read-only, write-only, and read-write properties.
1. Read-Only Property
A read-only property allows you to only retrieve the value of a field. To create a read-only property, you should define the get accessor.
Example
using System;
class Student
{
// Private field
private string _name;
// Read-only property
public string Name
{
get { return _name; }
}
// Constructor to set the read-only property
public Student(string name)
{
_name = name;
}
}
class Program
{
static void Main()
{
Student student = new Student("Ankita");
Console.WriteLine("Student Name: " + student.Name);
// The following line will give an error because the property is read-only:
// student.Name = "Rahul"; // Uncommenting this will cause a compilation error.
}
}
Output
Student Name: Ankita
2. Write-Only Property
A write-only property allows you to only change the value of a field. To create a write-only property, you should define the set accessor.
Example
using System;
class Employee
{
// Private field
private decimal _salary;
// Write-only property
public decimal Salary
{
set { _salary = value; }
}
// Method to display salary (could be restricted in real-world scenarios)
public void DisplaySalary()
{
Console.WriteLine("Salary: " + _salary);
}
}
class Program
{
static void Main()
{
Employee employee = new Employee();
// Setting the salary using the write-only property
employee.Salary = 50000m;
// Displaying the salary using a method (read access is not allowed directly)
employee.DisplaySalary();
// The following line would cause an error because the property is write-only:
// Console.WriteLine(employee.Salary); // Uncommenting this will cause a compilation error.
}
}
Output
Salary: 50000
3. Auto-implemented property
- Auto-implemented properties were introduced with C# 3.0, which makes property declaration more concise.
- Unlike standard property, in auto-implemented property, a wrapped or backing field is automatically created by the compiler, but it is not available for use by the class's members.
- public int Name { get; set; }.
Syntax
public <data_type> PropertyName { get; set; }
Example
using System;
class Car
{
// Auto-implemented property for CarName
public string CarName { get; set; }
// Auto-implemented property with default value
public int ModelYear { get; set; } = 2024;
}
class Program
{
static void Main()
{
// Creating an object of Car class
Car myCar = new Car();
// Setting value to auto-implemented property
myCar.CarName = "Honda";
// Getting value from auto-implemented property
Console.WriteLine("Car Name: " + myCar.CarName);
// Getting auto-implemented property with default value
Console.WriteLine("Model Year: " + myCar.ModelYear);
}
}
Output
Car Name: Honda
Model Year: 2024
4. Static property
You can also declare a property static. To make a static property, you must ensure that the backing store field is also static. Typically, a static property is used to make a singleton class.
using System;
class Bank
{
// Static property
public static decimal InterestRate { get; set; }
// Instance method to display the interest rate
public void DisplayInterestRate()
{
Console.WriteLine("Current Interest Rate: " + InterestRate + "%");
}
}
class Program
{
static void Main()
{
// Setting the static property using the class name
Bank.InterestRate = 4.5m;
// Creating instances of the Bank class
Bank bank1 = new Bank();
Bank bank2 = new Bank();
// Displaying the static property (same for all instances)
bank1.DisplayInterestRate();
bank2.DisplayInterestRate();
// Updating the static property
Bank.InterestRate = 5.0m;
// Displaying the updated interest rate
bank1.DisplayInterestRate();
bank2.DisplayInterestRate();
}
}
Output
Current Interest Rate: 4.5%
Current Interest Rate: 4.5%
Current Interest Rate: 5.0%
Current Interest Rate: 5.0%
5. Abstract property
An abstract property declaration does not provide an implementation of the property accessors. It leaves the implementation of the accessor to derived classes. Abstract properties are declared within an abstract class or interface.
Example
using System;
abstract class Shape
{
// Abstract property for calculating the area
public abstract double Area { get; }
// Abstract property for calculating the perimeter
public abstract double Perimeter { get; }
}
class Circle : Shape
{
private double radius;
// Constructor to initialize the radius
public Circle(double radius)
{
this.radius = radius;
}
// Implementing the abstract Area property
public override double Area
{
get { return Math.PI * radius * radius; }
}
// Implementing the abstract Perimeter property
public override double Perimeter
{
get { return 2 * Math.PI * radius; }
}
}
class Program
{
static void Main()
{
// Creating a Circle object
Circle circle = new Circle(5);
// Accessing the implemented properties
Console.WriteLine("Circle Area: " + circle.Area);
Console.WriteLine("Circle Perimeter: " + circle.Perimeter);
}
}
Output
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Some Other Examples of C# Properties
1. C# Feature with Polymorphism
In C#, polymorphism allows derived classes to provide specific implementations for properties or methods that are defined in a base class. Using properties, you can implement runtime polymorphism with the help of virtual, override, and abstract keywords.
Example
using System;
class Animal
{
// Virtual property allows overriding in derived classes
public virtual string Sound { get; set; }
// Method to describe the sound
public void MakeSound()
{
Console.WriteLine("Animal makes sound: " + Sound);
}
}
class Dog : Animal
{
// Overriding the Sound property
public override string Sound
{
get { return "Bark"; }
}
}
class Cat : Animal
{
// Overriding the Sound property
public override string Sound
{
get { return "Meow"; }
}
}
class Program
{
static void Main()
{
// Polymorphism using base class reference and derived class objects
Animal myAnimal;
myAnimal = new Dog();
myAnimal.MakeSound(); // Output: Animal makes sound: Bark
myAnimal = new Cat();
myAnimal.MakeSound(); // Output: Animal makes sound: Meow
}
}
Output
Animal makes sound: Bark
Animal makes sound: Meow
2. C# Feature with Inheritance
In C#, inheritance is one of the key features of Object-Oriented Programming (OOP) that allows a class to inherit members (fields, methods, properties, etc.) from another class. This promotes code reuse, helps organize and structure programs, and allows for the implementation of polymorphism.
Example
using System;
class Vehicle // Base class
{
public string Brand { get; set; }
// Method in the base class
public void StartEngine()
{
Console.WriteLine(Brand + " engine started.");
}
}
// Derived class inheriting from Vehicle
class Car : Vehicle
{
public string Model { get; set; }
// Method in the derived class
public void DisplayInfo()
{
Console.WriteLine("Brand: " + Brand + ", Model: " + Model);
}
}
class Program
{
static void Main()
{
// Creating an instance of the derived class
Car myCar = new Car();
// Accessing base class members from the derived class
myCar.Brand = "Honda"; // Inherited from Vehicle
myCar.Model = "Civic"; // Specific to Car
// Calling methods
myCar.StartEngine(); // Inherited method from Vehicle
myCar.DisplayInfo(); // Method in Car class
}
}
Output
Honda engine started.
Brand: Honda, Model: Civic
When to use Properties in C#
- Need to validate data before assigning it to a field.
- Data needs to be immediately computed before assigning or retrieving it to a field.
- Need to log all access for a field. Need to protect a field by reading and writing.
Advantages of properties in C#
- It provides better control of class members and avoids the complexity of the code.
- It ensures the security of the data fields.
- It also validates the data before storing it in the data fields.
- Fields are made read-only or write-only using the properties.
- Properties also make the program flexible, which means the programmer can change one part of the code without affecting other parts.
Read More: |
OOPs Interview Questions and Answers in C# |
Top 50 C# Interview Questions and Answers To Get Hired |
Conclusion
In conclusion, we can see that C# properties play a crucial role in encapsulating data, providing a structured way to manage access to class fields while enhancing code readability and maintainability. Their flexibility in implementation, along with support for inheritance and polymorphism, makes them an essential feature of object-oriented programming in C#. For mastering in C#, Scholarhat provides a Full-Stack .NET Developer Certification Training Course.
FAQs
Take our Csharp skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.