C# Properties (GET, SET) - Tutlane (2024)

In c#, Property is an extension of the class variable. Itprovides a mechanism to read, write, or change the class variable's valuewithout affecting the external way of accessing it in our applications.

In c#, properties can contain one or two code blocks called accessors, andthose are called a get accessor and set accessor. By using get and set accessors, we can change the internal implementation of classvariablesand expose them without affecting the external way of accessing it based on our requirements.

Generally, in object-oriented programming languages like c#, you need to define fields as privateand then use properties to access their values in apublic way with get and set accessors.

Following is the syntax of defining a property with get and set accessor in c# programming language.

<access_modifier> <return_type> <property_name>
{
get
{
//Return the property value
}
set
{
//Set a new value
}
}

If you observe the above syntax, we used an access modifier andreturn type to define a property along with get and set accessors to make required modifications to the classvariablesbased on our requirements.

Here, the get accessor code block will be executed whenever the property is read, and the code block of set accessor will be executed whenever the property is assigned to a new value.

In c#, the properties are categorized into three types, those are.

TypeDescription
Read-WriteA property that contains a both get and set accessors, then we will call it a read-write property.
Read-OnlyA property that contains only get accessor, then we will call it a read-only property.
Write-OnlyA property that contains only set accessor, then we will call it a write-only property.

In c#, Properties won’t accept any parameters, and we should not pass a property as a ref or out parameter in our application.

Following is a simple example of defining a private variable and a property in the c# programming language.

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

If you observe the above example, we defined a property called “Name” and we used a get accessor to return a property value and set accessors to set a new value. Here, the valuekeywordinsetaccessor is used to define a value that is being assigned bysetaccessor.

In c#, thegetaccessor needs to be used only to return the field value or to compute it and return it, but we should not use it for changing the state of an object.

As discussed, we can extend the behavior of classvariablesusing propertiesgetandsetaccessors. Following is the example of extending the behavior of privatevariablein property usinggetandsetaccessorsin c# programming language.

class User
{
private string name = "Suresh Dasari";
public string Name
{
get
{
return name.ToUpper();
}
set
{
if (value == "Suresh")
name = value;
}
}
}

If you observe the above example, we are extending the behavior of privatevariablename using a property called Name with get and set accessors by performing some validations like making sure theName value equals to only “Suresh” using set accessor and converting property text to uppercase with get accessor.

Here the field “name” is marked as private, so if you want to make any changes to this field, we can do it only by calling the property (Name).

In c# properties, thegetaccessor will be invoked while reading the value of a property, and when we assign a new value to the property, then thesetaccessor will be invoked by using an argument that provides the new value.

Following is an example of invokinggetandsetaccessors of properties in c# programming language.

User u = new User();
u.Name = "Rohini"; // set accessor will invoke
Console.WriteLine(u.Name); // get accessor will invoke

In the above example, when we assign a new value to the property, then thesetaccessor will be invoked and thegetaccessor will be invoked when we try to read the value from the property.

C# Properties (Get, Set) Example

Following is an example of defining propertieswithgetandsetaccessors to implement required validations without affecting the external way of using it in the c# programming language.

using System;

namespace Tutlane
{
class User
{
private string location;
private string name = "Suresh Dasari";
public string Location
{
get { return location; }
set { location = value; }
}
public string Name
{
get
{
return name.ToUpper();
}
set
{
if (value == "Suresh")
name = value;
}
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
// set accessor will invoke
u.Name = "Rohini";
// set accessor will invoke
u.Location = "Hyderabad";
// get accessor will invoke
Console.WriteLine("Name: " + u.Name);
// get accessor will invoke
Console.WriteLine("Location: " + u.Location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}

If you observe the above example, we are extending the behavior of privatevariables(name, location) using properties (Name, Location) withgetandsetaccessors by performing some validations like making sure Name value equals to only “Suresh” usingsetaccessor and converting property text to uppercase withgetaccessor.

When you execute the above c# program, we will get the result below.

C# Properties (GET, SET) - Tutlane (1)

If you observe the above example, our variable text converted to upper case, and even after we set the variable text as “Rohini”, it displayed text as “Suresh Dasari” because of thesetaccessor validation fails in the property.

C# Create Read-Only Properties

As discussed, if a property contains the onlygetaccessor, then we will call it aread-only property.Following is the example of creatingread-onlypropertiesin the c# programming language.

using System;

namespace Tutlane
{
class User
{
private string name;
private string location;
public User(string a, string b)
{
name = a;
location = b;
}
public string Name
{
get
{
return name;
}
}
public string Location
{
get
{
return location;
}
}
}
class Program
{
static void Main(string[] args)
{
User u = new User("Suresh Dasari", "Hyderabad");
// compile error
// u.Name = "Rohini";
// get accessor will invoke
Console.WriteLine("Name: " + u.Name);
// get accessor will invoke
Console.WriteLine("Location: " + u.Location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}

If you observe the above example, we created properties using onlygetaccessor to make the propertiesread-onlybased on our requirements.

If we uncomment the commented code, we will get a compile error because our Name property doesn’t contain anysetaccessor to set a new value. It’s justread-onlyproperty.

When you execute the above c# program, you will get a result as shown below.

C# Properties (GET, SET) - Tutlane (2)

This is how we can createread-onlyproperties in c# applications based on our requirements.

C# Create Write Only Properties

As discussed, if a property contains the onlysetaccessor, then we will call it a write-only property.Following is the example of creating write-only propertiesin the c# programming language.

using System;

namespace Tutlane
{
class User
{
private string name;
public string Name
{
set
{
name = value;
}
}
private string location;
public string Location
{
set
{
location = value;
}
}
public void GetUserDetails()
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Location: " + location);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
u.Name = "Suresh Dasari";
u.Location = "Hyderabad";
// compile error
//Console.WriteLine(u.Name);
u.GetUserDetails();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}

If you observe the above example, we created properties using onlysetaccessor to make the properties are write-only based on our requirements.

If we uncomment the commented code, then we will get a compile error because our Name property doesn’t contain anygetaccessor to return a value. It’s a just write-only property.

When you execute the above c# program, you will get a result like as shown below.

C# Properties (GET, SET) - Tutlane (3)

This is how we can create write-only properties in c# applications based on our requirements.

C# Auto Implemented Properties

In c#, a property is called an auto-implemented property when it contains accessors (get, set) without having any logic implementation.

Generally, the auto-implemented properties are useful whenever there is no logic implementation required in property accessors.

Following is the example of creating auto-implemented properties in the c# programming language.

using System;

namespace Tutlane
{
class User
{
public string Name { get; set; }
public string Location { get; set; }
}
class Program
{
static void Main(string[] args)
{
User u = new User();
u.Name = "Suresh Dasari";
u.Location = "Hyderabad";
Console.WriteLine("Name: " + u.Name);
Console.WriteLine("Location: " + u.Location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}

If you observe the above example, we created properties withgetandsetaccessors without having any logic implementation.

When you execute the above c# program, we will get a result like as shown below.

C# Properties (GET, SET) - Tutlane (4)

This is how we can create auto-implemented properties in c# applications based on our requirements.

C# Properties Overview

The following are the important points that we need to remember about properties in the c# programming language.

  • In c#, properties will enable class variables to expose in a public way usinggetandsetaccessors by hiding implementation details.
  • In properties, agetaccessor is used to return a property value and asetaccessor is used to assign a new value.
  • Thevaluekeywordinsetaccessor is used to define a value that is going to be assigned by thesetaccessor.
  • In c#, the properties are categorized as read-write, read-only, or write-only.
C# Properties (GET, SET) - Tutlane (2024)

FAQs

Why do we use get set property in C#? ›

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. An init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.

How to set values in properties in C#? ›

It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter. The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.

How to get all object properties in C#? ›

You can do this by getting an array of all properties from the Type. GetProperties method and then iterating the elements in the array, or you can retrieve the PropertyInfo object that represents the property directly by calling the Type. GetProperty method and specifying the property name.

How to make properties read only in C#? ›

To create a read-only field, use the readonly keyword in the definition. In the case of a field member, you get only one chance to initialize the field with a value, and that is when you call the class constructor. Beyond that, you'll would get an error for such attempt.

Why use get and set instead of public? ›

In OOP is considered a bad practice to have public attribute. Get and set create two methods to change and get properties, but consent you to simulate a public attribute, because you can use a property like it. This helps you when you decide to change your internal logic, without change your exposed methods.

What is the difference between get and set properties? ›

get is for when you return the value of a property. set is for when you assign a value to a property. A property that is described as { get } is a read-only property. A property that is described as { set } is a write-only property.

How to get properties dynamically in C#? ›

In C#, you can access dynamic properties by obtaining a PropertyObject reference from the specific object reference using the AsPropertyObject method on the object. You can then use the PropertyObject interface to access custom properties of the object using a lookup string to specify the specific custom property.

How do getters and setters work in C#? ›

Understanding What Setters and Getters Do in C#

Simply put, a getter (get) fetches the value of a variable, while a setter (set) assigns a value to it.

What is the difference between properties and fields 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.

How to access properties in C#? ›

The object of the class MyClass can access property X as follows. MyClass mc = new MyClass(); mc. X = 10; // calls set accessor of the property X, and pass 10 as value of the standard field 'value'. This is used for setting the value for the data member x.

How to get PropertyInfo in C#? ›

GetProperties() Method

Syntax: public System. Reflection. PropertyInfo[] GetProperties (); Return Value: This method returns an array of PropertyInfo objects representing all public properties of the current Type or an empty array of type PropertyInfo if the current Type does not have public properties.

What does GetProperties() return in C#? ›

GetProperties() Returns all the public properties of the current Type.

Can we override properties in C#? ›

C# supports overriding on instance methods and properties but not on fields or on any static members. It requires an explicit action within both the base class and the derived class. The base class must mark each member for which it allows overriding as virtual.

Can properties be private in C#? ›

Properties can be marked as public , private , protected , internal , protected internal , or private protected .

What does => mean in C#? ›

In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.

Why use get and set? ›

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value.

What is the use of set in C#? ›

set (C# Reference)

The set keyword defines an accessor method in a property or indexer that assigns a value to the property or the indexer element. For more information and examples, see Properties, Auto-Implemented Properties, and Indexers.

Why should we use properties in C#? ›

Properties have many uses: They can validate data before allowing a change. They can transparently expose data on a class where that data is retrieved from some other source, such as a database. They can take an action when data is changed, such as raising an event, or changing the value of other fields.

Top Articles
Latest Posts
Article information

Author: Rev. Leonie Wyman

Last Updated:

Views: 5597

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.