Properties in C#

Properties in C#

23 May 2024
Intermediate
115K Views
8 min read
Learn via Video Course & by Doing Hands-on Labs

C# Programming For Beginners Free Course

Properties in C#: An Overview

A Property acts as a wrapper around a field. It 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 property can be created for a public, private, protected, and internal field. So in this C# Tutorial, we will explore more about properties in C# which will include,c# property with real-life examples, Different types of properties, when to use property with example, advantage of the property, What is a static property, and abstract property.

What is Property in C#?

  • Properties are used for a class to expose a public way of getting and setting values while hiding implementation or verification code.
  • To return the property value, a get property accessor is used and a set property accessor is used to assign a new value.
  • An init property accessor is for assigning a new value only during object construction. These accessors can have different kinds of access levels.
  • Properties can be read-write(get, set), read-only(get), or write-only(set).
  • Write-only properties are used to restrict access to sensitive data.
  • Properties do not denote storage locations and you cannot pass a property as a ref or out parameter.

Example of Properties:

Let's elaborate properties in C# Compiler with its example:
using System;
class Example
{
 string name;
 public string Name
 {
 get { return name; }
 set { name = value; }
 }
}

class Program
{
 static void Main()
 {
 Example obj= new Example();
 obj.Name = "ScholarHat"; // called set { }
 Console.WriteLine(obj.Name); // called get { }
 }
}   

Output

 Scholarhat

Read More - C# Programming Interview Questions

Different types of properties

Properties can be divided into three categories 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.

     class Example
    {
     string name;
     public string Name
     {
     get { return name; }
     }
    }
    
  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.

     class Example
    {
     string name;
     public string Name
     {
     set{ name = value; }
     }
    }
    
  3. Read-Write Property

    A read-write property allows you to assign and read the value of a field. To create a read-write property, you should define the set and get accessors.

     class Example
    {
     string name;
     public string Name
     {
     get { return name; }
     set { name = value; }
     }
    }
    

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; }

To make an auto-implemented property read-only or write-only, you need to specify both get and set accessors.

 public int ReadOnly { get; private set; }
public int WriteOnly { private get; set; } 

Simply, you need to store a value. No additional functionality can be added to either of the accessors.

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.

 public class Singleton
{
 private static Singleton instance = new Singleton();
 private Singleton() { }
 
 public static Singleton GetInstance
 {
 get { return instance; }
 }}

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.

 public abstract class Person
{
 public abstract string Name{ get; set;}
 
}

class Student : Person
{
 private string name;
 
 // Override Name property 
 public override string Name
 {
 get { return name; }
 set { name = value; }
 }
}
 
 
public interface IPerson
{
 string Name { get; set; }

}

class Student : IPerson
{
 private string name;

 // implement Name property 
 public string Name
 {
 get { return name; }
 set { name = value; }
 }
} 
 

When to use Properties in C#

  • Need to validate data before assigning it to a field.
  • Need to do intermediate computation on data 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#

  1. It provides better control of class members and avoids the complexity of the code.
  2. It ensures the security of the data fields.
  3. It also validates the data before storing it in the data fields.
  4. Fields made of read-only or write-only using the properties.
  5. Properties also make the program flexible, which means the programmer can change one part of the code without affecting other parts.
    Conclusion
    I hope you will enjoy the property in C# while programming. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. Also, consider our course C# Programming for a better understanding of C# Concepts.

    FAQs

    Q1. What is field and property in C#?

    In C#, a field is a variable (that can be of any type) that is defined inside a class. It can be used to define the characteristics of an object or a class. On the other hand, a property is a member of the class that provides an abstraction to set (write) and get (read) the value of a private field.

    Q2. What is public properties in C#?

    A property is a (usually public) member of a class that provides (most commonly) a way to read or write the value of a private field or (less commonly) to compute a value from private fields.

    Q3. Why use properties in C#?

     Because they can validate data before allowing a change.

    Q4. What are properties in programming?

     Special attributes or characteristics associated with an object.

    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.

    GET FREE CHALLENGE

    Share Article

    Live Classes Schedule

    Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
    ASP.NET Core Certification Training Jul 15 MON, WED, FRI
    Filling Fast
    07:00AM to 08:30AM (IST)
    Get Details
    Advanced Full-Stack .NET Developer Certification Training Jul 15 MON, WED, FRI
    Filling Fast
    07:00AM to 08:30AM (IST)
    Get Details
    Azure Master Class Jul 20 SAT, SUN
    Filling Fast
    03:00PM to 05:00PM (IST)
    Get Details
    ASP.NET Core Certification Training Jul 28 SAT, SUN
    Filling Fast
    07:00AM to 09:00AM (IST)
    Get Details
    Software Architecture and Design Training Jul 28 SAT, SUN
    Filling Fast
    05:30PM to 07:30PM (IST)
    Get Details
    .NET Solution Architect Certification Training Jul 28 SAT, SUN
    Filling Fast
    05:30PM to 07:30PM (IST)
    Get Details
    Azure Developer Certification Training Jul 28 SAT, SUN
    Filling Fast
    10:00AM to 12:00PM (IST)
    Get Details
    Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
    Filling Fast
    07:00AM to 09:00AM (IST)
    Get Details
    Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
    Filling Fast
    08:30PM to 10:30PM (IST)
    Get Details
    Angular Certification Course Aug 11 SAT, SUN
    Filling Fast
    09:30AM to 11:30AM (IST)
    Get Details
    ASP.NET Core Certification Training Aug 24 SAT, SUN
    Filling Fast
    07:00AM to 09:00AM (IST)
    Get Details

    Can't find convenient schedule? Let us know

    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

    Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
    Accept cookies & close this