This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Using Properties (C# Programming Guide)

  • 16 contributors

Properties combine aspects of both fields and methods. To the user of an object, a property appears to be a field; accessing the property requires the same syntax. To the implementer of a class, a property is one or two code blocks, representing a get accessor and/or a set or init accessor. The code block for the get accessor is executed when the property is read; the code block for the set or init accessor is executed when the property is assigned a value. A property without a set accessor is considered read-only. A property without a get accessor is considered write-only. A property that has both accessors is read-write. You can use an init accessor instead of a set accessor to enable the property to be set as part of object initialization but otherwise make it read-only.

Unlike fields, properties aren't classified as variables. Therefore, you can't pass a property as a ref or out parameter.

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.

Properties are declared in the class block by specifying the access level of the field, followed by the type of the property, followed by the name of the property, and followed by a code block that declares a get -accessor and/or a set accessor. For example:

In this example, Month is declared as a property so that the set accessor can make sure that the Month value is set between 1 and 12. The Month property uses a private field to track the actual value. The real location of a property's data is often referred to as the property's "backing store." It's common for properties to use private fields as a backing store. The field is marked private in order to make sure that it can only be changed by calling the property. For more information about public and private access restrictions, see Access Modifiers . Auto-implemented properties provide simplified syntax for simple property declarations. For more information, see Auto-Implemented Properties .

The get accessor

The body of the get accessor resembles that of a method. It must return a value of the property type. The C# compiler and Just-in-time (JIT) compiler detect common patterns for implementing the get accessor, and optimizes those patterns. For example, a get accessor that returns a field without performing any computation is likely optimized to a memory read of that field. Auto-implemented properties follow this pattern and benefit from these optimizations. However, a virtual get accessor method can't be inlined because the compiler doesn't know at compile time which method might actually be called at run time. The following example shows a get accessor that returns the value of a private field _name :

When you reference the property, except as the target of an assignment, the get accessor is invoked to read the value of the property. For example:

The get accessor must be an expression-bodied member, or end in a return or throw statement, and control can't flow off the accessor body.

It's a bad programming style to change the state of the object by using the get accessor.

The get accessor can be used to return the field value or to compute it and return it. For example:

In the previous example, if you don't assign a value to the Name property, it returns the value NA .

The set accessor

The set accessor resembles a method whose return type is void . It uses an implicit parameter called value , whose type is the type of the property. The compiler and JIT compiler also recognize common patterns for a set or init accessor. Those common patterns are optimized, directly writing the memory for the backing field. In the following example, a set accessor is added to the Name property:

When you assign a value to the property, the set accessor is invoked by using an argument that provides the new value. For example:

It's an error to use the implicit parameter name, value , for a local variable declaration in a set accessor.

The init accessor

The code to create an init accessor is the same as the code to create a set accessor except that you use the init keyword instead of set . The difference is that the init accessor can only be used in the constructor or by using an object-initializer .

Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property. The get and set accessors for the same property can have different access modifiers. For example, the get might be public to allow read-only access from outside the type, and the set can be private or protected . For more information, see Access Modifiers .

A property can be declared as a static property by using the static keyword. Static properties are available to callers at any time, even if no instance of the class exists. For more information, see Static Classes and Static Class Members .

A property can be marked as a virtual property by using the virtual keyword. Virtual properties enable derived classes to override the property behavior by using the override keyword. For more information about these options, see Inheritance .

A property overriding a virtual property can also be sealed , specifying that for derived classes it's no longer virtual. Lastly, a property can be declared abstract . Abstract properties don't define an implementation in the class, and derived classes must write their own implementation. For more information about these options, see Abstract and Sealed Classes and Class Members .

It is an error to use a virtual , abstract , or override modifier on an accessor of a static property.

This example demonstrates instance, static, and read-only properties. It accepts the name of the employee from the keyboard, increments NumberOfEmployees by 1, and displays the Employee name and number.

Hidden property example

This example demonstrates how to access a property in a base class that is hidden by another property that has the same name in a derived class:

The following are important points in the previous example:

  • The property Name in the derived class hides the property Name in the base class. In such a case, the new modifier is used in the declaration of the property in the derived class: public new string Name
  • The cast (Employee) is used to access the hidden property in the base class: ((Employee)m1).Name = "Mary";

For more information about hiding members, see the new Modifier .

Override property example

In this example, two classes, Cube and Square , implement an abstract class, Shape , and override its abstract Area property. Note the use of the override modifier on the properties. The program accepts the side as an input and calculates the areas for the square and cube. It also accepts the area as an input and calculates the corresponding side for the square and cube.

  • Interface Properties
  • Auto-Implemented Properties

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

C# Tutorial

C# examples, c# properties (get and set), properties and encapsulation.

Before we start to explain properties, you should have a basic understanding of " Encapsulation ".

  • declare fields/variables as private
  • provide public get and set methods, through properties , to access and update the value of a private field

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, sometimes we need to access them - and it can be done with properties.

A property is like a combination of a variable and a method, and it has two methods: a get and a set method:

Example explained

The Name property is associated with the name field. 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.

If you don't fully understand it, take a look at the example below.

Now we can use the Name property to access and update the private field of the Person class:

The output will be:

Try it Yourself »

Advertisement

Automatic Properties (Short Hand)

C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get; and set; inside the property.

The following example will produce the same result as the example above. The only difference is that there is less code:

Using automatic properties:

Why Encapsulation?

  • Better control of class members (reduce the possibility of yourself (or others) to mess up the code)
  • Fields can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • Flexible: the programmer can change one part of the code without affecting other parts
  • Increased security of data

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Dot Net Tutorials

Properties in C#

Back to: C#.NET Tutorials For Beginners and Professionals

Properties in C# with Examples

In this article, I am going to discuss the Properties in C# with Examples. Please read our previous article before proceeding to this article where we discussed the Const and Read-Only Variables in C#. As part of this article, we are going to discuss the following pointers related to properties in detail.

Why do we need Properties in C#?

What is a property in c#, what are accessors in c#, what is a set accessor.

  • What is a Get Accessor?
  • What are the different types of Properties supported by C#.NET?
  • What is Read-Only Property?
  • What is Write Only property?
  • What is the Read Write property?
  • What are the Advantages of using Properties in C#?
  • What is the default accessibility modifier of Accessors in C#?
  • What are Symmetric and Asymmetric Accessors in C#?

What are Auto-Implemented Properties in C#?

  • Why do we need Properties in real-time applications with an example?

In order to encapsulate and protect the data members (i.e. fields or variables) of a class, we use properties in C#. The Properties in C# are used as a mechanism to set and get the values of data members of a class outside of that class. If a class contains any values in it and if we want to access those values outside of that class, then we can provide access to those values in 2 different ways. They are as follows:

  • By storing the value under a public variable, we can give direct access to the value outside of the class.
  • By storing that value in a private variable, we can also give access to that value outside of the class by defining a property for that variable.

A Property in C# is a member of a class that is used to set and get the data from a data field (i.e. variable) of a class. The most important point that you need to remember is that a property in C# is never used to store any data, it just acts as an interface or medium to transfer the data. We use the Properties as they are public data members of a class, but they are actually special methods called accessors.

The Assessors are nothing but special methods which are used to set and get the values from the underlying data member (i.e. variable) of a class. Assessors are of two types. They are as follows:

  • Set Accessor
  • Get Accessor

The  set  accessor is used to set the data (i.e. value) into a data field i.e. a variable of a class. This set accessor contains a fixed variable named value . Whenever we call the property to set the data, whatever data (value) we are supplying will come and store inside the variable called value by default. Using a set accessor, we cannot get the data.

Syntax:  set { Data_Field_Name = value; }

What is Get Accessor?

The get accessor is used to get the data from the data field i.e. variable of a class. Using the get accessor, we can only get the data, we cannot set the data.

Syntax:  get {return Data_Field_Name;}

Example to Understand Properties in C#:

In the below example, I have shown you the use of Properties in C#. Here, we have created two classes i.e. Employee and Program and we want to access the Employee class data members inside the Program class. In the Employee class, we have created two private data members (i.e. _EmpId and _EmpName ) to hold the Employee Id and Name of the Employee and as we mark these two variables as private, so we cannot access directly these two members from outside the Employee class. We cannot access them directly from the Program class. Then for these two data members, we have created two public properties i.e. EmpId and EmpName to get and set the Employee ID and Name respectively. The point that you need to remember is properties are not going to store the value, rather they are just transferring the values. The variables are going to store the data. Further, the following example code is self-explained, so please go through the comments line.

Example to Understand Properties in C#

Now, you may have one question. Why not make the variables public? Why are we are creating the variables as private and why we are creating public properties for them? The answer is to achieve the Encapsulation Principle. We will discuss this in detail when we discuss the Encapsulation Principle in C# .

What are the Different types of Properties Supported by C#.NET?

The C#.NET supports four types of properties. They are as follows

  • Read-Only Property
  • Write Only Property
  • Read Write Property
  • Auto-Implemented Property

Let us understand each of the above properties in detail with examples.

What is Read-only Property in C#?

The Read-Only Property is used to read the data from the data field i.e. read the data of a variable. Using this Read-Only Property, we cannot set the data into the data field. This property will contain only one accessor i.e. get accessor. Syntax: AccessModifier Datatype PropertyName {       get {return DataFieldName;} }

What is Write only Property in C#?

The Write-Only Property is used to write the data into the data field i.e. write the data to a variable of a class. Using this Write-Only Property, we cannot read the data from the data field. This property will contain only one accessor i.e. set accessor. Syntax: AccessModifier Datatype PropertyName {        set {DataFieldName = value;} }

What is Read Write Property in C#?

The Read-Write Property is used for both reading the data from the data field as well as writing the data into the data field of a class. This property will contain two accessors i.e. set and get. The set accessor is used to set or write the value to a data field and the get accessor is read the data from a variable. Syntax: AccessModifier Datatype PropertyName {       set {DataFieldName = value;}       get {return DataFieldName;} }

Note: Whenever we create a property for a variable, the data type of the property must be the same as the data type of the variable. A property can never accept any argument.

Example to understand the Read and Write Property in C#

In the below example, within the Employee class, we have created four private variables and for private each variable we have created public properties. And we have created each property with both set and get accessors which will make them read and write property and using these properties we can perform both read and write operations. The point that you need to remember is the data type of the property and the data of the corresponding variables must be the same, or else you will get a compile-time error. Then from the Main method, we create an instance of the Employee class, and then by using the public properties we are setting the getting values.

Example to understand the Read and Write Property in C#

In the above example, we declare the data fields i.e. variables of Employee class as private. As a result, these data fields or variables are not accessible directly from outside the Employee class. So, here, in the Program class which is outside of the Employee class, we transferred the data into the data field or variables with the help of properties. 

Example to understand the Read-Only and Write-Only Properties in C#:

In the below example, within the Calculator class, we have created three private variables. Then for these three private variables, we have created two write-only properties (property with only set accessor) for _Number1 and _Number2 variables and one read-only property (property with only get accessor) for _Result variable. Using the write-only property we can only set the values and using only the read-only property we can get the value. Then from the Main method of the Program class, we create an instance of the Calculator class and access the read-only and write-only properties.

What are the advantages of using Properties in C#?

  • Properties will provide the abstraction to the data fields.
  • They also provide security to the data fields.
  • Properties can also validate the data before storing it in the data fields.

Note: When we will discuss the Encapsulation OOPs Principle , at that time, I will explain the above points with practical examples.

What is the Default Accessibility Specifier of Accessors in C#?

The default accessibility specifier of the accessor is the same as the accessibility specifier of the property. For example: public int EmpId {      set { _EmpId = value; }      get {  return _EmpId; } } In the above example, the property Empid is declared as public. So, the set and get accessor will be public. If the property is private then both set and get accessors will also be private.

What are symmetric and asymmetric accessors in C#?

If the accessibility specifier of the accessors (both get and set) are the same within a property accessibility specifier then the accessors are known as symmetric accessors. On the other hand,  if the accessibility specifier of the accessors is not the same as a property accessibility specifier, then the accessors are known as asymmetric accessors. For example:

public int EmpId {       protected set { _EmpId = value; }       get { return _EmpId; } }

In the above property, the set accessor is declared as protected while the get accessor is public by default, so they are known as asymmetric. In general, asymmetric accessors are used in the inheritance process. We will discuss this in detail when we discuss Inheritance OOPs Principle in C#.

We can also write the Read-only property using two accessors as follows. public int EmpId {       private set { _EmpId = value; }       get { return _EmpId; } }

We can also write the Write only property using two accessors as follows. public int EmpId {       set { _EmpId = value; }       private get { return _EmpId; } }

Note: The point that you need to remember is once you declare the accessor as private, then you cannot access that accessor from outside the class.

If you do not have any additional logic while setting and getting the data from a data field i.e. from a variable of a class, then you can make use of the auto-implemented properties which was introduced as part of C# 3.0. The Auto-Implemented Property in C# reduces the amount of code that we have to write. When we use auto-implemented properties, then the C# compiler implicitly creates a private, anonymous field or variable for that property behind the scene which is going to hold the data. Syntax: Access_specifier Datatype Property_Name { get; set; } Example: public int A { get; set; }

Example to understand Auto Implemented Properties in C#:

In the below example, I am showing the use of Auto Implemented Properties in C#. Please observe the Employee class. In the Employee class, we have not created any private data fields or variables to hold the data. But we have created four Auto Implemented Properties. When we create Auto Implemented Properties, behind the scene, the compiler will create the private anonymous field for each property to hold the data.

Now, if you verify the IL code of the Employee class using the ILDASM tool, then you will see that four private variables are created behind scenes by the compiler as shown in the below image.

Why do we need Properties in C# Real-time Applications?

Declaring the class fields or variables as public and exposing those fields or variables to the outside world (which means outside of the class) is bad as we do not have any control over what gets assigned and what gets returned. Let’s understand this with one example.

Problems with the above public fields are as follows

  • An ID value should always be a non-negative number.
  • The name cannot be set to NULL.
  • If a student’s name is missing then we should return “No Name”.
  • The PassMark value should always be read-only.

The Programming Languages like C++, and Java does not have the concept properties and such programming languages use getter and setter methods to encapsulate and protect fields.

Example using Setter and Getter Methods in C#:

Let’s rewrite the previous example using setter and getter methods to achieve the above requirements. For each variable or data field, we need to write setter or getter methods as per our requirements. Here, we have written setter and getter methods for _ID and _Name variables to set and get the ID and Name values. On the other hand, we have only getter methods for the _PassMark variable, so from outside the class, we cannot set the value for PassMark. Again, within the setter and getter properties, we have also written logic to validate the data before storing and returning.

Example using Properties in C#:

The advantage of properties over the traditional getter() and setter() methods is that we can access them as they are public fields, not methods. Let’s rewrite the same program using properties to achieve the same requirements.

In the next article, I am going to discuss the use of the ToString() Method in C# and then we will discuss why we should override the ToString method in C# with some examples. Here, in this article, I try to explain Properties in C# with Examples. I hope you understood the need and use of Properties in C#.

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

3 thoughts on “Properties in C#”

It is worth noting one subtle thing: you cannot throw exceptions within a set accessor method. This means that you cannot introduce validation errors on class instantiation.

For example, suppose you have a class such as:

Public class Exam { private readonly int _studentId; private readonly int _grade;

public int Id { get; set; } public int Grade { get{ return _studentId; } set{ _studentId = value >= 0 && value <= 10 ? value : throw new FormatException(); } // <— you can't do this }

// […] }

Hi, It is possible to throw exceptions within a set accessor. Please check out last example and to introduce the exception, please set a negative number for the Id value.

Thank you so much you explain in such a wordy and lucid way, please keep on posting tutorials, you guys are so AMAZING!!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Popular Articles

  • C# Guid (Dec 08, 2023)
  • C# Factory Pattern (Dec 08, 2023)
  • C# Filestream (Dec 08, 2023)
  • C# Entity Framework (Dec 08, 2023)
  • C# Event Handler (Dec 08, 2023)

C# Property

Switch to English

Table of Contents

Introduction

Understanding c# properties, property accessibility, tips and common pitfalls.

  • Defining Properties
  • Auto-implemented Properties
  • Read-Only Properties
  • Write-Only Properties
  • Property vs Field
  • Null Reference Exception
  • Infinite Loop in Property Accessor

Home » C# Tutorial » C# Property

C# Property

Summary : in this tutorial, you’ll about the C# property and how to use the properties effectively.

Introduction to the C# property

By definition, a property is a member of a class that provides a flexible way to read, write, or compute the value of a private field.

For example, the following defines the class Person with three private fields firstName , lastName , and age :

To assign values to and read values from these private fields, you use properties. The following shows how to add three properties to the Person class:

In this example, we declare a property like a field with a get and set blocks. The get and set are called the property accessors.

When you read from a property, the get accessor executes. And when you assign a value to a property, the set accessor executes. For example:

In this example:

  • First, create an instance of the Person class.
  • Second, assign the values to the FirstName and LastName properties.
  • Third, read values from the FirstName and LastName properties.

Using C# property for data validation

Since a property provides a central place to assign a value to a private field, you can validate the data and throw an exception if the data is not valid.

Suppose you want to implement the following validation rules:

  • The first name and last name are not null or empty
  • The age is between 1 and 150

To do that, you can add the validation logic to the set accessors of the properties as shown in the following example:

The following program causes an exception because the age is out of the valid range (1-150)

C# computed property

To create a computed property, you can implement the get accessor. For example, you can create a FullName property that returns the concatenation of the first name and last name:

And you can read from the FullName property:

If you attempt to assign a value to the FullName property, you’ll get a compilation error. For example:

C# auto-implemented properties

If you have a property that requires no additional logic in the set or get accessors, you can use an auto-implemented property.

The following example defines the Skill class that has two private fields name and rating , and the corresponding properties:

Since the accessors of the properties have no additional logic besides reading from and writing to private fields, you can use auto-implemented properties like this:

When the C# compiler encounters an auto-implemented property, it creates a private, anonymous field that can be accessed through the set and get accessors.

As you can see, the auto-implemented properties make the code more concise in this case.

In C# 9 or later, you can init an auto-implemented property like this:

In this example, we initialize the Rating property so that its value is one when you create a new instance of the Skill class.

  • A property is a member of a class that provides a flexible way to read, write, or compute the value of a private field.
  • A property contains get and/or set accessors.
  • The get accessor executes when you read the value from the property while the set accessor executes when you assign a value to the property.
  • Use auto-implemented property if the get and set accessors have no additional logic to make the code more concise.
  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

C# Property

last modified January 31, 2024

In this article we show how to work with properties in C#.

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.

Properties use accessors through which the values of the private fields can be read, written or manipulated. Property reads and writes are translated to get and set method calls. Properties shield the data from the outside world while having a convenient field access.

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. The init property accessor is used to assign a new value only during object construction. The value keyword is used to define the value that is assigned by the set or init accessor.

Properties can be read-write (they have both a get and a set accessor), read-only (they have only a get accessor), or write-only (they have only a set accessor).

C# Property with backing field

The following example uses a property with a backing field.

We have the Name property with the _name backing field.

We create an instance of the User class. We access the member field using the field notation.

We have a property that is called Name . It looks like a regular method declaration. The difference is that it has specific accessors called get and set .

The get property accessor is used to return the property value and the set accessor is used to assign a new value. The value keyword is used to define the value being assigned by the set accessor.

C# read-only property

To create a read-only property, we omit the set accessor and provide only the get accessor in the implementation.

In the example, we have read-only properties. Once initialized in the constructor, they cannot be modified.

We make the property read-only by providing a get accessor only.

C# auto-implemented properties

C# has auto-implemented or automatic properties. With automatic properties, the compiler transparently provides the backing fields for us.

This code is much shorter. We have a User class in which we have two properties: Name and Occupation .

We normally use the properties as usual.

Here we have two automatic properties. There is no implementation of the accessors and there are no member fields. The compiler will do the rest for us.

C# init-only property

The init keyword is used to create init-only properties; these properties can be initialized only during object construction.

We define two init-only properties; they are initialized at the object construction. Later, they become immutable.

We use the primary constructor. It gives us two parameters: name and occupation . They are later used to initialize properties.

The init-only properties are created with the init keyword.

C# required properties

The required keyword is used to force the clien to implement the property.

We must use object initializers to create an object with a required property.

C# expression body definitions

Properties can be simplified with expression body definitions. Expression body definitions consist of the => symbol followed by the expression to assign to or retrieve from the property.

In the example, we use the expression body definitions to define properties for the User class.

Other notes

We can mark properties with access modifiers like public , private or protected . Properties can be also static , abstract , virtual and sealed . Their usage is identical to regular methods.

In the preceding example, we define a virtual property and override it in the Derived class.

The Name property is marked with the virtual keyword.

We are hiding a member in the Derived class. To suppress the compiler warning, we use the new keyword.

And here we override the Name property of the Base class.

Properties - programming guide

In this article we have covered C# properties.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials .

assign property c#

Refactor your code with C# collection expressions

assign property c#

May 8th, 2024 7 8

This post is the second in a series of posts covering various refactoring scenarios that explore C# 12 features. In this post, we’ll look at how you can refactor your code using collection expressions, we’ll learn about collection initializers, various expression usages, supported collection target types, and the spread syntax. Here’s how the series is shaping up:

  • Refactor your C# code with primary constructors
  • Refactor your C# code with collection expressions (this post)
  • Refactor your C# code by aliasing any type
  • Refactor your C# code to use default lambda parameters

These features continue our journey to make our code more readable and maintainable, and these are considered “Everyday C#” features that developers should know.

Collection Expressions 🎨

C# 12 introduced collection expressions that offer a simple and consistent syntax across many different collection types. When initializing a collection with a collection expression, the compiler generates code that is functionally equivalent to using a collection initializer. The feature emphasizes consistency , while allowing for the compiler to optimize the lowered C#. Of course, every team decides what new features to adopt, and you can experiment and introduce this new syntax if you like it, since all of the previous ways to initialize collections will continue to work.

With collections expressions elements appear inlined sequences of elements between an opening [ and closing ] bracket. Read on to hear more about how collection expressions work.

Initialization 🌱

C# provides many syntaxes for initializing different collections. Collection expressions replace all of these, so let’s start with a look at different ways you can initialize an array of integers like this:

All four versions are functionally equivalent, and the compiler generates identical code for each version. The last example is similar to the new collection expressions syntax. If you squint your eyes a bit, you could imagine the curly braces as { and } as square brackets [ and ] , then you’d be reading the new collection expression syntax. Collection expressions don’t use curly braces. This is to avoid ambiguity with existing syntax, especially { } to indicate any not-null in patterns.

The last example is the only to declare the type explicitly, instead of relying on var . The following example creates a List<char> :

Again, collection expressions cannot be used with the var keyword. You must declare the type because a collection expression doesn’t currently have a natural type and can be converted to a wide variety of collection types . Supporting assignment to var is still under consideration, but the team has not settled on the what the natural type should be. In other words, the C# compiler errors out with CS9176: There is no target type for the collection expression, when writing the following code:

You might be asking yourself, “with all these different approaches to initializing collections, why would I use the new collection expression syntax?” The answer is that with collection expressions, you can use the same syntax to express collections in a consistent way. This can help to make your code more readable and maintainable. We’ll explore more advantages in the coming sections.

Collection expression variations 🎭

You can express that a collection is empty , using the following syntax:

The empty collection expression initialization is a great replacement for code that was otherwise using the new keyword, as it’s optimized by the compiler to avoid allocating memory for some collection types. For example, when the collection type is an array T[] , the compiler generates an Array.Empty<T>() , which is more efficient than new int[] { } . Another shortcut is to use the number of elements in the collection expression to set the collection size, such as new List<int>(2) for List<T> x = [1, 2]; .

Collection expressions also allow you to assign to interfaces without stating an explicit type. The compiler determines the type to use for types, such as IEnumerable<T> , IReadOnlyList<T> , and IReadOnlyCollection<T> . If the actual type used is important, you’ll want to state it because this may change if more efficient types become available. Likewise, in situations where the compiler cannot generate more efficient code, for example when the collection type is a List<T> , the compiler generates a new List<int>() , which is then equivalent.

The advantages of using the empty collection expression are threefold:

  • It provides a consistent means of initializing all collections, regardless of their target type.
  • It allows the compiler to generate efficient code.
  • It’s less code to write. For example, instead of writing Array.Empty<T>() or Enumerable.Empty<T>() , you can simply write [] .

A few more details about the efficient generated code: using the [] syntax generates known IL. This allows the runtime to optimize by reusing the storage for Array.Empty<T> (for each T ), or even more aggressively inline the code.

Empty collections serve their purpose, but you may need a collection that has some initial values. You can initialize a collection with a single element, using the following syntax:

Initializing a single element collection is similar to initializing a collection with more than a single element. You can initialize a collection with multiple elements by adding other literal values, using the following syntax:

A bit of history

Let’s look at another code sample, but this uses spread element , to include the elements of another collection, using the following syntax:

The spread element is a powerful feature that allows you to include the elements of another collection in the current collection. The spread element is a great way to combine collections in a concise way. The expression in a spread element must be enumerable ( foreach -able). For more information, see the Spread ✨ section.

Supported collection types 🎯

There are many target types that collection expressions can be used with. The feature recognizes the “shape” of a type that represents a collection. Therefore, most collections you’re familiar with are supported out-of-the-box. For types that don’t match that “shape” (mostly readonly collections), there are attributes you can apply to describe the builder pattern. The collection types in the BCL that needed the attributes/builder pattern approaches, have already been updated.

It’s unlikely that you’ll ever need to think about how target types are selected, but if you are curious about the rules see the C# Language Reference: Collection expressions—conversions .

Collection expressions don’t yet support dictionaries. You can find a proposal to extend the feature C# Feature Proposal: Dictionary expressions .

Refactoring scenarios 🛠️

Collection expressions can be useful in many scenarios, such as:

  • properties.
  • local variables.
  • method parameters.
  • return values.
  • a coalescing expression as the final fallthrough to safely avoid exceptions.
  • Passing arguments to methods that expect collection type parameters.

Let’s use this section to explore some sample usage scenarios, and consider potential refactoring opportunities. When you define a class or struct that contains fields and/or properties with non-nullable collection types, you can initialize them with collection expressions. For example, consider the following example ResultRegistry object:

In the preceding code, the result registry class contains a private _results field that is initialized with a new HashSet<Result>() constructor expression. In your IDE of choice (that supports these refactoring features), right-click on the new keyword, select Quick Actions and Refactorings... (or press Ctrl + . ), and choose Collection initialization can be simplified , as shown in the following video:

The code is updated to use the collection expression syntax, as shown in the following code:

The previous code, instantiated the HashSet<Result> with the new HashSet<Result>() constructor expression. However, in this case [] is identical.

Many popular programming languages such as Python and JavaScript/TypeScript, among others provide their variation of the spread syntax, which serves as a succinct way to work with collections. In C#, the spread element is the syntax used to express the concatenation of various collections into a single collection.

Proper terminology

So what exactly is spread element ? It takes the individual values from the collection being “spread” and places them in the destination collection at that position. The spread element functionality also comes with a refactoring opportunity. If you have code that calls .ToList or .ToArray , or you want to use eager evaluation, your IDE might be suggesting to use the spread element syntax instead. For example, consider the following code:

The preceding code could be refactored to use the spread element syntax, consider the following code that removes the .ToList method call, and uses an expression-bodied method as a bonus refactored version:

Span<T> and ReadOnlySpan<T> support 📏

Collection expressions support Span<T> and ReadOnlySpan<T> types that are used to represent a contiguous region of arbitrary memory. You benefit from the performance improvements they offer, even if you don’t use them directly in your code. Collection expressions allow the runtime to offer optimizations, especially where overloads using span can be selected when collection expressions are used as arguments.

You can also assign directly to span, if your application uses spans:

If you’re using the stackalloc keyword, there’s even a provided refactoring to use collection expressions. For example, consider the following code:

If you right-click on the stackalloc keyword, select Quick Actions and Refactorings... (or press Ctrl + . ), and choose Collection initialization can be simplified , as shown in the following video:

https://devblogs.microsoft.com/dotnet/wp-content/uploads/sites/10/2024/05/refactor-collection-ex.mp4

For more information, see Memory<T> and Span<T> usage guidelines .

Semantic considerations ⚙️

When initializing a collection with a collection expression, the compiler generates code that is functionally equivalent to using a collection initializer. Sometimes the generated code is much more efficient than using a collection initializer. Consider the following example:

The rules for a collection initializer require that the compiler call the Add method for each element in the initializer. However, if you’re to use the collection expression syntax:

The compiler generates code that instead uses AddRange , that might be faster or better optimized. The compiler is able to make these optimizations because it knows the target type of the collection expression.

Next steps 🚀

Be sure to try this out in your own code! Check back soon for the next post in this series, where we’ll explore how to refactor your C# code by aliasing any type. In the meantime, you can learn more about collection expressions in the following resources:

  • C# Feature Proposal: Collection expressions
  • C# Language Reference: Collection expressions
  • C# Docs: Collections

assign property c#

David Pine Senior Content Developer, .NET

assign property c#

Leave a comment Cancel reply

Log in to join the discussion or edit/delete existing comments.

This is all extremely nice!

This is a neat implementation of the Collection expression.

IMHO this is the annoying part of the feature Again, collection expressions cannot be used with the var keyword.

hope this will be addressed sooner then later, and if that’s all the reason behind it but the team has not settled on the what the natural type should be.

roll a dice if you can’t make up your mind. Or put up a poll and let majority decide.

I disagree. var support is not needed.

If anyone is wondering, the question is which is the correct choice when var is used: a) Default to the fastest and most efficient, such as Span or ReadOnlySpan b) Default to the one with the best developer experience, such as List

You can argue both cases, so it is just hard for everyone to reach agreement here.

Love or hate the collection expressions, but the use of emojis here is world class.

Regarding the LINQ example with the spread operator: does use of the collection expression result in the same call to .ToList() or is there some additional optimization going on? The original code could have been written as expression-bodied member as well, without declaring a local variable, so the new syntax isn’t much shorter and arguably the intent isn’t really clearer either. I wouldn’t use collection expressions in that case, unless perhaps it’s more efficient – hence the question.

(that aside, a very useful feature! the spread operator will replace a bunch of help methods in our code that were used to combine individual items and lists into a single list in an efficient manner, glad to let the compiler do that now)

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

Elektrostal (Q198419)

assign property c#

Wiktionary (0 entries)

Multilingual sites (0 entries).

assign property c#

  • Pages with maps

Navigation menu

Expedia Rewards is now One Key™

Elektrostal, visit elektrostal, check elektrostal hotel availability, popular places to visit.

  • Electrostal History and Art Museum

You can spend time exploring the galleries in Electrostal History and Art Museum in Elektrostal. Take in the museums while you're in the area.

  • Cities near Elektrostal

Photo by Ksander

  • Places of interest
  • Yuri Gagarin Cosmonaut Training Center
  • Central Museum of the Air Forces at Monino
  • Peter the Great Military Academy
  • History of Russian Scarfs and Shawls Museum
  • Balashikha Arena
  • Ramenskii History and Art Museum
  • Balashikha Museum of History and Local Lore
  • Bykovo Manor
  • Pekhorka Park
  • Malenky Puppet Theater
  • Drama Theatre BOOM
  • Pavlovsky Posad Museum of Art and History
  • Saturn Stadium
  • Likino Dulevo Museum of Local Lore
  • Noginsk Museum and Exhibition Center
  • Fairy Tale Children's Model Puppet Theater
  • Fifth House Gallery
  • Church of Vladimir
  • Malakhovka Museum of History and Culture
  • Orekhovo Zuevsky City Exhibition Hall

assign property c#

PEKIN, Elektrostal - Lenina Ave. 40/8 - Restaurant Reviews, Photos & Phone Number - Tripadvisor

IMAGES

  1. C# : Assign Property with an ExpressionTree

    assign property c#

  2. C# : C# Automatically assign property based on other property values

    assign property c#

  3. Properties In C# With Examples: ReadOnly, WriteOnly Properties in C#

    assign property c#

  4. C# : Using Moq to assign property value when method is called

    assign property c#

  5. reference

    assign property c#

  6. c#

    assign property c#

VIDEO

  1. Auto Implemented Property

  2. PROPERTY ASSIGN IN ETAB/01

  3. C# Properties: Everything You Need To Know

  4. C++ Assignment Operators Practice coding

  5. C# Tutorial

  6. C++ Variables, Literals, an Assignment Statements [2]

COMMENTS

  1. Using Properties

    Properties combine aspects of both fields and methods. To the user of an object, a property appears to be a field; accessing the property requires the same syntax. To the implementer of a class, a property is one or two code blocks, representing a get accessor and/or a set or init accessor. The code block for the get accessor is executed when ...

  2. c#

    ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter. Usage: For setting up the properties directly under the object root: Ie.

  3. C# Properties (Get and Set)

    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. If you don't fully understand it, take a look at ...

  4. Properties in C# with Examples

    In the below example, I have shown you the use of Properties in C#. Here, we have created two classes i.e. Employee and Program and we want to access the Employee class data members inside the Program class. In the Employee class, we have created two private data members (i.e. _EmpId and _EmpName) to hold the Employee Id and Name of the ...

  5. Understanding and Using C# Properties

    Properties in C# are a powerful feature and an integral part of object-oriented programming (OOP). They can be seen as a hybrid between a variable and a method. ... `Name` is a property, and `name` is a field. The value keyword represents the value we assign to the property. Auto-implemented Properties; If there is no additional logic in the ...

  6. C# property

    Second, assign the values to the FirstName and LastName properties. Third, read values from the FirstName and LastName properties. Using C# property for data validation. Since a property provides a central place to assign a value to a private field, you can validate the data and throw an exception if the data is not valid.

  7. C# Property

    C# Property tutorial shows how to work with properties in C#. A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. ... and a set property accessor is used to assign a new value. The init property accessor is used to assign a new value only during object construction.

  8. methods

    .Net - Reflection set object property Setting a property by reflection with a string value. I have an object with multiple properties. Let's call the object objName. I'm trying to create a method that simply updates the object with the new property values. I want to be able to do the following in a method:

  9. Refactor your code with C# collection expressions

    The spread element is often confused with the term "spread operator". In C#, there's no such thing as a "spread operator". The .. expression isn't an operator, it's an expression that's part of the spread element syntax. By definition, this syntax doesn't align with that of an operator, as it doesn't perform an operation on its operands.

  10. Elektrostal

    All structured data from the main, Property, Lexeme, and EntitySchema namespaces is available under the Creative Commons CC0 License; text in the other namespaces is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply.

  11. C# : assign data to properties via constructor vs. instantiating

    15. Second approach is object initializer in C#. Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The first approach. var albumData = new Album("Albumius", "Artistus", 2013);

  12. ELEKTROSTAL HOTEL

    See all properties. LOCATION. Russia Central Russia Moscow Oblast Elektrostal. NUMBER OF ROOMS. 19. Prices are the average nightly price provided by our partners and may not include all taxes and fees. Taxes and fees that are shown are estimates only. Please see our partners for more details.

  13. Visit Elektrostal: 2024 Travel Guide for Elektrostal, Moscow ...

    Cities near Elektrostal. Places of interest. Pavlovskiy Posad Noginsk. Travel guide resource for your visit to Elektrostal. Discover the best of Elektrostal so you can plan your trip right.

  14. c#

    In c# 6.0 you can now do. string username = SomeUserObject?.Username; username will be set to null if SomeUSerObject is null. If you want it to get the value "", you can do ... This code will not assign the property in case the value is null. This is useful for when null has a special meaning of 'skip this property'.

  15. PEKIN, Elektrostal

    Pekin. Review. Save. Share. 17 reviews #12 of 28 Restaurants in Elektrostal $$ - $$$ Asian. Lenina Ave., 40/8, Elektrostal 144005 Russia +7 495 120-35-45 Website + Add hours Improve this listing. See all (5) Enhance this page - Upload photos! Add a photo.

  16. c#

    160. You could cheat and make life easier with an extension method: public static void SetPropertyValue<T, TValue>(this T target, Expression<Func<T, TValue>> memberLamda, TValue value) var memberSelectorExpression = memberLamda.Body as MemberExpression;