Code Maze

  • Blazor WASM 🔥
  • ASP.NET Core Series
  • GraphQL ASP.NET Core
  • ASP.NET Core MVC Series
  • Testing ASP.NET Core Applications
  • EF Core Series
  • HttpClient with ASP.NET Core
  • Azure with ASP.NET Core
  • ASP.NET Core Identity Series
  • IdentityServer4, OAuth, OIDC Series
  • Angular with ASP.NET Core Identity
  • Blazor WebAssembly
  • .NET Collections
  • SOLID Principles in C#
  • ASP.NET Core Web API Best Practices
  • Top REST API Best Practices
  • Angular Development Best Practices
  • 10 Things You Should Avoid in Your ASP.NET Core Controllers
  • C# Back to Basics
  • C# Intermediate
  • Design Patterns in C#
  • Sorting Algorithms in C#
  • Docker Series
  • Angular Series
  • Angular Material Series
  • HTTP Series
  • .NET/C# Author
  • .NET/C# Editor
  • Our Editors
  • Leave Us a Review
  • Code Maze Reviews

Select Page

How to Get a Value of a Property By Using its Name in C#

Posted by Code Maze | Jan 25, 2024 | 0

How to Get a Value of a Property By Using its Name in C#

In programming, there are scenarios where dynamically retrieving the value of a property by its name becomes necessary. This guide delves into the intricacies of how to get the value of a property by using its name in C# using reflection . Assuming we have a foundational understanding of C# and reflection, we’ll skip exhaustive explanations of basic concepts. We will set up a simple console application to demonstrate this useful capability in C#.

Let’s dive in.

Retrieve Property Value By Name

To start, let’s consider a simple Person class:

We define a Person class with public fields and a single private field. We aim to retrieve property values from an instance of this class dynamically.

To retrieve the value of a public property by its name, let’s create a utility method:

Become a patron at Patreon!

To start with, we define a generic utility method, which means it can return properties of any type. Initially, the method checks if the provided obj object is null. This step is crucial to avoid a NullReferenceException . After ensuring the object is not null, we attempt to retrieve the public property information using reflection with the GetProperty() method. If the property doesn’t exist, we promptly inform the caller and exit gracefully.

Furthermore, it’s important to ensure that the property’s type matches the expected type TType . We achieve this using the is not operator, which checks if the property value can be cast to type TType .

In addition, if the property value is null and the expected type TType is nullable, we handle this scenario correctly. In such a way we ensure that we gracefully manage null values. Finally, if all checks pass, the property value is cast to type TType and assigned to the output parameter, thereby completing the process.

Finally, to test this out, let’s create an instance of the type Person and use our utility method to retrieve the value of Age property:

We pass the person object and Age string as the property name and we log the result to the console.

Upon inspecting the console, we will observe:

Retrieved value: 18. 

Please note, that the provided TryGetPropertyValue() the method only works for public instance properties retrieval. So, instance and static private properties and protected properties will not be found . To make it work with instance and static private properties and protected properties,  we can add BindingFlags to the GetProperty() method call:

PropertyInfo? propertyInfo = typeof(TObj).GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

Handling Edge Cases

There are cases like property renaming, removal, and changes in type that can pose significant hurdles when trying to retrieve values. We already handled those cases in our method, but let’s just explicitly mention those.

Property Rename or Removal

When we use reflection in C# to access properties, handling scenarios where a property gets renamed or removed is crucial. Let’s consider a situation where we attempt to retrieve a non-existent Address property using our utility method:

PropertyRetrieval.TryGetPropertyValue<string>(person, "Address", out var value);

When we run the program and inspect the console, we will observe:

Property 'Address' not found.

Changing Property Type

Handling changes in property types is crucial, so, let’s test out our utility method for a case where we try to retrieve a property with a wrong type:

PropertyRetrieval.TryGetPropertyValue<string>(person, "IsDeleted", out var value);

Here we attempt to retrieve the value of IsDeleted property as a string type, however, we know IsDeleted is a boolean.

Upon running the program and inspecting the console, we observe the message:

Property 'IsDeleted' is of type System.Boolean, got System.String.

In this guide, we have explored how to get the value of a property by using its name in C#, furthermore, we used a concise and pragmatic approach, moreover, we have considered edge cases and handled them with finesse.

Remember, reflection comes with performance considerations, and its usage should be reasonable. The provided utility method serves as a tool, ready to tackle dynamic property retrieval challenges.

guest

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices .

MAKOLYTE

Solve real coding problems

C# – Using reflection to get properties

You can get a list of a type’s properties using reflection, like this:

Note: If you have an object, use movie.GetType().GetProperties() instead.

This outputs the following:

When you use GetProperties(), it returns a list of PropertyInfo objects. This gives you access the property’s definition (name, type, etc…) and allows you to get and modify its value.

In this article, I’ll show examples of using reflection to look for and use properties.

Table of Contents

Get and modify property values

You can use PropertyInfo.GetValue() / SetValue() to get and modify property values.

I’ll show examples of getting / modifying properties on the following Movie object:

Get property values

Use PropertyInfo.GetValue() to get a property’s value.

This example is getting all properties and their values:

Note: Notice the difference between reflecting a type’s properties vs reflecting an object’s properties (typeof(movie).GetProperties() vs movie.GetType().GetProperties()).

This outputs the property names and values:

Modify property values

Use PropertyInfo.SetValue() to modify a property’s value.

This example is modifying the Movie.Director property value:

This outputs the updated property value:

Problems to avoid

There are a few things to watch out for when using PropertyInfo.SetValue() / GetValue(). I’ll show examples in the sections below.

Set the right type

Movie.Id is an integer, and this is trying to set its value to a string:

This results in the following exception:

System.ArgumentException: Object of type ‘System.String’ cannot be converted to type ‘System.Int32’

To avoid this problem, convert the value to the right type. PropertyInfo.PropertyType tells you the right type, and you can use Convert.ChangeType() as a general purpose way to convert from one type to another:

Note: If you know specifically what type you are converting to, you can use the specific converter instead if you want (like Convert.ToInt32()), instead of the general purpose Convert.ChangeType().

Avoid modifying a read-only property

Let’s say Movie.BoxOfficeRevenue is read-only and you’re trying to modify it:

The behavior depends on how you defined the read-only property.

Surprisingly, you can modify the property’s value when it has a private setter (same behavior as a readonly field):

Note: This is technically not a read-only property, but you may want to avoid modifying its value from the outside, since declaring it with a private setter was probably done for a reason.

You can’t modify the value if the property doesn’t have a setter (a true read-only property):

You’ll get the following the exception:

System.ArgumentException: Property set method not found.

To avoid this, you can check PropertyInfo.SetMethod:

It’ll be null if there’s no setter, and SetMethod.IsPrivate will be true if it was declared with a private setter.

Check for nulls

GetProperty(name) returns null if it can’t find a property with the specified name, which can lead to NullReferenceException’s.

Let’s say BoxOfficeRevenue is defined as a readonly field:

And you mistakenly use GetProperty() to fetch this field :

Since BoxOfficeRevenue is a field , not a property , GetProperty() will return null. Since it’s trying to call .GetValue() on a null, it results in a NullReferenceException.

To avoid this problem, check if the PropertyInfo is null before using it.

Filter properties by definition (name, type, etc…)

There are two main ways to filter properties:

  • Pass in the BindingFlags enum flag parameter to control what GetProperties() looks for.
  • Filter the returned PropertyInfo objects by looking at its properties, such as PropertyInfo.PropertyType.

By default, GetProperties() returns all public instance and static properties of a type. When you pass in the BindingFlags parameter, it overrides the default behavior. So make sure to pass in ALL of the flags you want, including re-adding the default behavior if desired (ex: BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).

I’ll show a few filtering examples below.

Get a specific property by name

If you want a specific property by name, use GetProperty() instead of GetProperties().

This outputs:

By default, GetProperty() does a case sensitive search. You can do a case insensitive search like this by using BindingFlags.IgnoreCase, like this:

This matched “releasedOn” with the ReleasedOn property and output:

Get all private properties

Let’s say you want to get the following private instance properties:

To get these properties, use GetProperties() with these BindingFlags:

This outputs the two private properties:

Get all properties with a specific type

Let’s say you want to get all DateTime properties.

To do that, filter by PropertyInfo.PropertyType in a Where():

Get all properties that have a setter

Let’s say you want to modify property values, so you only want to get properties that have a setter. For example, you want to filter out the following read-only property:

To exclude read-only properties, filter by PropertyInfo.SetMethod in a Where():

This outputs all of the properties that have a setter:

Get properties that have an attribute

You can use PropertyInfo.GetCustomAttribute<T>() to check if properties have an attribute.

For example, let’s say you have the following two properties that have the [Required] attribute:

Note: [Required] is one of many built-in model validation attributes .

Here’s how to filter out properties that don’t have the [Required] attribute:

Related Articles

  • C# – Get types from assembly (reflection-only load)
  • C# – How to call a static method using reflection
  • C# – Get subclass properties with reflection
  • C# – Check if a property is an enum with reflection
  • C# – Get all classes with a custom attribute

2 thoughts on “C# – Using reflection to get properties”

Excellent article!

Leave a Comment Cancel reply

CODE SNIPPETS

All the Code Snippets and Samples you need

How to set a Property Value by Name in C# and VB.NET

' src=

By Administrator

To set a Property Value by Name in C# and VB.NET you can use the following snippet.

Sample VB.NET

Related post, how to export gridview data to excel using devexpress xtragrid, how to catch specific ms-sql sqlexceptions in c# and vb.net, how to extract a password protected zip file using dotnetzip in c# and vb.net, 2 thought on “how to set a property value by name in c# and vb.net”.

RT @CodeSnippetsNET: How to set a Property Value by Name in C# and #VB .NET http://t.co/1evOj3lbnf #csharp #dotnet #dev

Leave a Reply Cancel reply

You must be logged in to post a comment.

Dave Brock

  • ASP.NET Core
  • Blast Off With Blazor
  • .NET Stacks

Exploring C# 10: Use Extended Property Patterns to Easily Access Nested Properties

Dave Brock

Welcome back to my series on new C# 10 features. So far we've talked about file-scoped namespaces and global using declarations . Today, we'll talk about extended property patterns in C# 10.

Over the last few years, C# has made a lot of property pattern enhancements. Starting with C# 8, the language has supported extended property patterns , a way to match an object's specific properties.

For our example, let's continue the superhero theme with a Person , a Superhero that inherits from Person , and a Suit . We're going to calculate any special surcharges when making a particular superhero's suit.  

Now let's create a quick object for Iron Man:

In our switch expression, let's say we want to determine special pricing based on a particular suit's color.

Here's how we'd do it in C# 9:

With C# 10, we can use dot notation to make it a bit cleaner:

Much like before, you can also use multiple expressions at once. Let's say we wanted to charge a surcharge for a notoriously difficult customer. Look at how we can combine multiple properties in a single line.

That's all there is to it. Will this feature change your life? No. Even so, it's a nice update that allows for cleaner and simpler code.

There's a lot more you can do with property patterns as well, so I'd recommend hitting up the Microsoft Docs to learn more.

c# assign property by name

If you're interested in the design proposal, you can also find it below.

c# assign property by name

Let me know your thoughts below. Happy coding!

Featured Posts

Low ceremony, high value: a tour of minimal apis in .net 6.

Low Ceremony, High Value: A Tour of Minimal APIs in .NET 6

Ask About Azure: Why do resource groups need a location?

Ask About Azure: Why do resource groups need a location?

Use Azure Functions with .NET 5

Use Azure Functions with .NET 5

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

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

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.
  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

How to set a property value by reflection in C#?

The System. Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application.

Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System. Reflection namespace.

Reflection allows view attribute information at runtime.

Reflection allows examining various types in an assembly and instantiate these types.

Reflection allows late binding to methods and properties.

Reflection allows creating new types at runtime and then performs some tasks using those types.

GetProperty(String)

Searches for the public property with the specified name.

GetType(String, Boolean)

Gets the Type object with the specified name in the assembly instance and optionally throws an exception if the type is not found.

SetValue(Object, Object)

Sets the property value of a specified object.

Nizamuddin Siddiqui

Related Articles

  • How to set a property having different datatype with a string value using reflection in C#?
  • How to fetch a property value dynamically in C#?
  • How to set align-self property to its default value in CSS?
  • How to delete an element from the Set by passing its value in C++
  • Reflection in C#
  • How to Invoke Method by Name in Java Dynamically Using Reflection?
  • How do you give a C# Auto-Property a default value?
  • How to set a value to a file input in HTML?
  • Mirror Reflection in C++
  • Line Reflection in C++
  • How to display methods and properties using reflection in C#?
  • How to set result of a java expression in a property in JSP?
  • How to set Octet value in JavaTuples
  • Set a certain value first with MySQL ORDER BY?
  • How to set selected item of Spinner by value instead of by position on Android?

Kickstart Your Career

Get certified by completing the course

  • 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 .

c# assign property by name

Create a form in Word that users can complete or print

In Word, you can create a form that others can fill out and save or print.  To do this, you will start with baseline content in a document, potentially via a form template.  Then you can add content controls for elements such as check boxes, text boxes, date pickers, and drop-down lists. Optionally, these content controls can be linked to database information.  Following are the recommended action steps in sequence.  

Show the Developer tab

In Word, be sure you have the Developer tab displayed in the ribbon.  (See how here:  Show the developer tab .)

Open a template or a blank document on which to base the form

You can start with a template or just start from scratch with a blank document.

Start with a form template

Go to File > New .

In the  Search for online templates  field, type  Forms or the kind of form you want. Then press Enter .

In the displayed results, right-click any item, then select  Create. 

Start with a blank document 

Select Blank document .

Add content to the form

Go to the  Developer  tab Controls section where you can choose controls to add to your document or form. Hover over any icon therein to see what control type it represents. The various control types are described below. You can set properties on a control once it has been inserted.

To delete a content control, right-click it, then select Remove content control  in the pop-up menu. 

Note:  You can print a form that was created via content controls. However, the boxes around the content controls will not print.

Insert a text control

The rich text content control enables users to format text (e.g., bold, italic) and type multiple paragraphs. To limit these capabilities, use the plain text content control . 

Click or tap where you want to insert the control.

Rich text control button

To learn about setting specific properties on these controls, see Set or change properties for content controls .

Insert a picture control

A picture control is most often used for templates, but you can also add a picture control to a form.

Picture control button

Insert a building block control

Use a building block control  when you want users to choose a specific block of text. These are helpful when you need to add different boilerplate text depending on the document's specific purpose. You can create rich text content controls for each version of the boilerplate text, and then use a building block control as the container for the rich text content controls.

building block gallery control

Select Developer and content controls for the building block.

Developer tab showing content controls

Insert a combo box or a drop-down list

In a combo box, users can select from a list of choices that you provide or they can type in their own information. In a drop-down list, users can only select from the list of choices.

combo box button

Select the content control, and then select Properties .

To create a list of choices, select Add under Drop-Down List Properties .

Type a choice in Display Name , such as Yes , No , or Maybe .

Repeat this step until all of the choices are in the drop-down list.

Fill in any other properties that you want.

Note:  If you select the Contents cannot be edited check box, users won’t be able to click a choice.

Insert a date picker

Click or tap where you want to insert the date picker control.

Date picker button

Insert a check box

Click or tap where you want to insert the check box control.

Check box button

Use the legacy form controls

Legacy form controls are for compatibility with older versions of Word and consist of legacy form and Active X controls.

Click or tap where you want to insert a legacy control.

Legacy control button

Select the Legacy Form control or Active X Control that you want to include.

Set or change properties for content controls

Each content control has properties that you can set or change. For example, the Date Picker control offers options for the format you want to use to display the date.

Select the content control that you want to change.

Go to Developer > Properties .

Controls Properties  button

Change the properties that you want.

Add protection to a form

If you want to limit how much others can edit or format a form, use the Restrict Editing command:

Open the form that you want to lock or protect.

Select Developer > Restrict Editing .

Restrict editing button

After selecting restrictions, select Yes, Start Enforcing Protection .

Restrict editing panel

Advanced Tip:

If you want to protect only parts of the document, separate the document into sections and only protect the sections you want.

To do this, choose Select Sections in the Restrict Editing panel. For more info on sections, see Insert a section break .

Sections selector on Resrict sections panel

If the developer tab isn't displayed in the ribbon, see Show the Developer tab .

Open a template or use a blank document

To create a form in Word that others can fill out, start with a template or document and add content controls. Content controls include things like check boxes, text boxes, and drop-down lists. If you’re familiar with databases, these content controls can even be linked to data.

Go to File > New from Template .

New from template option

In Search, type form .

Double-click the template you want to use.

Select File > Save As , and pick a location to save the form.

In Save As , type a file name and then select Save .

Start with a blank document

Go to File > New Document .

New document option

Go to File > Save As .

Go to Developer , and then choose the controls that you want to add to the document or form. To remove a content control, select the control and press Delete. You can set Options on controls once inserted. From Options, you can add entry and exit macros to run when users interact with the controls, as well as list items for combo boxes, .

Adding content controls to your form

In the document, click or tap where you want to add a content control.

On Developer , select Text Box , Check Box , or Combo Box .

Developer tab with content controls

To set specific properties for the control, select Options , and set .

Repeat steps 1 through 3 for each control that you want to add.

Set options

Options let you set common settings, as well as control specific settings. Select a control and then select Options to set up or make changes.

Set common properties.

Select Macro to Run on lets you choose a recorded or custom macro to run on Entry or Exit from the field.

Bookmark Set a unique name or bookmark for each control.

Calculate on exit This forces Word to run or refresh any calculations, such as total price when the user exits the field.

Add Help Text Give hints or instructions for each field.

OK Saves settings and exits the panel.

Cancel Forgets changes and exits the panel.

Set specific properties for a Text box

Type Select form Regular text, Number, Date, Current Date, Current Time, or Calculation.

Default text sets optional instructional text that's displayed in the text box before the user types in the field. Set Text box enabled to allow the user to enter text into the field.

Maximum length sets the length of text that a user can enter. The default is Unlimited .

Text format can set whether text automatically formats to Uppercase , Lowercase , First capital, or Title case .

Text box enabled Lets the user enter text into a field. If there is default text, user text replaces it.

Set specific properties for a Check box .

Default Value Choose between Not checked or checked as default.

Checkbox size Set a size Exactly or Auto to change size as needed.

Check box enabled Lets the user check or clear the text box.

Set specific properties for a Combo box

Drop-down item Type in strings for the list box items. Press + or Enter to add an item to the list.

Items in drop-down list Shows your current list. Select an item and use the up or down arrows to change the order, Press - to remove a selected item.

Drop-down enabled Lets the user open the combo box and make selections.

Protect the form

Go to Developer > Protect Form .

Protect form button on the Developer tab

Note:  To unprotect the form and continue editing, select Protect Form again.

Save and close the form.

Test the form (optional)

If you want, you can test the form before you distribute it.

Protect the form.

Reopen the form, fill it out as the user would, and then save a copy.

Creating fillable forms isn’t available in Word for the web.

You can create the form with the desktop version of Word with the instructions in Create a fillable form .

When you save the document and reopen it in Word for the web, you’ll see the changes you made.

Facebook

Need more help?

Want more options.

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

c# assign property by name

Microsoft 365 subscription benefits

c# assign property by name

Microsoft 365 training

c# assign property by name

Microsoft security

c# assign property by name

Accessibility center

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

c# assign property by name

Ask the Microsoft Community

c# assign property by name

Microsoft Tech Community

c# assign property by name

Windows Insiders

Microsoft 365 Insiders

Was this information helpful?

Thank you for your feedback.

This browser is no longer supported.

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

Named and Optional Arguments (C# Programming Guide)

  • 22 contributors

Named arguments enable you to specify an argument for a parameter by matching the argument with its name rather than with its position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.

When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

Named and optional parameters enable you to supply arguments for selected parameters. This capability greatly eases calls to COM interfaces such as the Microsoft Office Automation APIs.

Named arguments

Named arguments free you from matching the order of arguments to the order of parameters in the parameter lists of called methods. The argument for each parameter can be specified by parameter name. For example, a function that prints order details (such as, seller name, order number & product name) can be called by sending arguments by position, in the order defined by the function.

If you don't remember the order of the parameters but know their names, you can send the arguments in any order.

Named arguments also improve the readability of your code by identifying what each argument represents. In the example method below, the sellerName can't be null or white space. As both sellerName and productName are string types, instead of sending arguments by position, it makes sense to use named arguments to disambiguate the two and reduce confusion for anyone reading the code.

Named arguments, when used with positional arguments, are valid as long as

they're not followed by any positional arguments, or

they're used in the correct position. In the example below, the parameter orderNum is in the correct position but isn't explicitly named.

Positional arguments that follow any out-of-order named arguments are invalid.

The following code implements the examples from this section along with some additional ones.

Optional arguments

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:

  • a constant expression;
  • an expression of the form new ValType() , where ValType is a value type, such as an enum or a struct ;
  • an expression of the form default(ValType) , where ValType is a value type.

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported. For example, in the following code, instance method ExampleMethod is defined with one required and two optional parameters.

The following call to ExampleMethod causes a compiler error, because an argument is provided for the third parameter but not for the second.

However, if you know the name of the third parameter, you can use a named argument to accomplish the task.

IntelliSense uses brackets to indicate optional parameters, as shown in the following illustration:

Screenshot showing IntelliSense quick info for the ExampleMethod method.

You can also declare optional parameters by using the .NET OptionalAttribute class. OptionalAttribute parameters do not require a default value. However, if a default value is desired, take a look at DefaultParameterValueAttribute class.

In the following example, the constructor for ExampleClass has one parameter, which is optional. Instance method ExampleMethod has one required parameter, required , and two optional parameters, optionalstr and optionalint . The code in Main shows the different ways in which the constructor and method can be invoked.

The preceding code shows a number of examples where optional parameters aren't applied correctly. The first illustrates that an argument must be supplied for the first parameter, which is required.

COM interfaces

Named and optional arguments, along with support for dynamic objects, greatly improve interoperability with COM APIs, such as Office Automation APIs.

For example, the AutoFormat method in the Microsoft Office Excel Range interface has seven parameters, all of which are optional. These parameters are shown in the following illustration:

Screenshot showing IntelliSense quick info for the AutoFormat method.

However, you can greatly simplify the call to AutoFormat by using named and optional arguments. Named and optional arguments enable you to omit the argument for an optional parameter if you don't want to change the parameter's default value. In the following call, a value is specified for only one of the seven parameters.

For more information and examples, see How to use named and optional arguments in Office programming and How to access Office interop objects by using C# features .

Overload resolution

Use of named and optional arguments affects overload resolution in the following ways:

  • A method, indexer, or constructor is a candidate for execution if each of its parameters either is optional or corresponds, by name or by position, to a single argument in the calling statement, and that argument can be converted to the type of the parameter.
  • If more than one candidate is found, overload resolution rules for preferred conversions are applied to the arguments that are explicitly specified. Omitted arguments for optional parameters are ignored.
  • If two candidates are judged to be equally good, preference goes to a candidate that doesn't have optional parameters for which arguments were omitted in the call. Overload resolution generally prefers candidates that have fewer parameters.

C# language specification

For more information, see the C# Language Specification . The language specification is the definitive source for C# syntax and usage.

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

IMAGES

  1. C# : C# Reflection get Field or Property by Name

    c# assign property by name

  2. C# : Assign Property with an ExpressionTree

    c# assign property by name

  3. c#

    c# assign property by name

  4. C#

    c# assign property by name

  5. c#

    c# assign property by name

  6. c#

    c# assign property by name

VIDEO

  1. PROPERTY ASSIGN IN ETAB

  2. Difference Between Field & Property In C# .Net

  3. And by KMart. The only marketing property name trusted for all quality products

  4. Write Only Property in C#

  5. Change your property name to accommodate your spouse? advisable ?

  6. C# Recursion Logic/ Communityforum, Post All Comment and All reply/ Company Reporting hierarchy

COMMENTS

  1. C# get and set property by variable name

    4 Answers Sorted by: 34 Yes, your looking for the PropertyInfo.SetValue method e.g. var propInfo = info.GetType ().GetProperty (propertyName); if (propInfo != null) { propInfo.SetValue (info, value, null); } Share Improve this answer Follow answered Aug 6, 2012 at 7:51 James 81.2k 18 168 239 Add a comment 10

  2. Using Properties

    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: C#

  3. How to Get a Value of a Property By Using its Name in C#

    value = default; if (obj is null) { Console.WriteLine("Object is null."); return false; } PropertyInfo? propertyInfo = typeof(TObj).GetProperty(propertyName); if (propertyInfo is null) { Console.WriteLine($"Property '{propertyName}' not found."); return false;

  4. C#

    GetProperty(name) returns null if it can't find a property with the specified name, which can lead to NullReferenceException's. Let's say BoxOfficeRevenue is defined as a readonly field: public readonly decimal BoxOfficeRevenue; Code language: C# (cs) And you mistakenly use GetProperty() to fetch this field:

  5. Properties in C#

    09/29/2022 14 contributors Feedback In this article Property syntax Validation Access control Read-only Show 6 more Properties are first class citizens in C#. The language defines syntax that enables developers to write code that accurately expresses their design intent. Properties behave like fields when they're accessed.

  6. Properties

    Properties overview Properties enable 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 property value, and a set property accessor is used to assign a new value.

  7. Setting a Property Value by Name in C# and VB.NET

    To set a Property Value by Name in C# and VB.NET you can use the following snippet. Sample C# 1 2 3 4 5 6 7 public static bool SetPropertyByName (this Object obj, string name, Object value) { var prop = obj.GetType ().GetProperty (name, BindingFlags.Public | BindingFlags.Instance); if (null == prop || !prop.CanWrite) return false;

  8. c#

    Accessing Properties by Name Asked 7 years, 1 month ago Modified 7 years ago Viewed 4k times 4 Over the weekend I decided to start work on my own version of FastMember. I began with my take on an implementation of TypeAccessor so that I could work with the properties of any type, create an instance of the type, and one or two other little tricks.

  9. c#

    2,801 9 36 73 Sounds like you need to look into reflection. Look at Type.GetProperty and Type.GetProperties to start with. - Jon Skeet Jun 25, 2013 at 19:16 1 The things you are trying to do are possible through reflection, but we'd like to see what you've learned so far trying to achieve this and where you are stuck - Adriano Carneiro

  10. Exploring C# 10: Use Extended Property Patterns to Easily Access Nested

    Today, we'll talk about extended property patterns in C# 10. Over the last few years, C# has made a lot of property pattern enhancements. Starting with C# 8, the language has supported extended property patterns, a way to match an object's specific properties. For our example, let's continue the superhero theme with a Person, a Superhero that ...

  11. C# Properties (Get and Set)

    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.

  12. Dynamically set property value in a class (C#)

    Rarely needed as in C# object types and properties are known although there are rare occasions this may be needed when dealing with data received with a property name as type string and value of type object. Example Using the following class and enum. public class Settings { public string UserName { get; set; }

  13. Assignment operators

    The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.

  14. C# property

    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

  15. c#

    public void setProperty (int index, int value) { string property = ""; if (index == 1) { // set the property X with 'value' property = "X"; } else { // set the property Z with 'value' property = "Z"; } A. {property} = value; } This is a silly example so please believe, I have an use for this. c# reflection system.reflection Share

  16. How to set a property value by reflection in C#?

    Searches for the public property with the specified name. GetType(String, Boolean) Gets the Type object with the specified name in the assembly instance and optionally throws an exception if the type is not found. SetValue(Object, Object) Sets the property value of a specified object.

  17. c#

    List<Argument> arguments = new List<Argument> { new Argument () {PropertyName = "AString", PropertyValue = "this is a string"}, new Argument () {PropertyName = "AnInt", PropertyValue = 1729}, new Argument () {PropertyName = "ADirInfo", PropertyValue = new DirectoryInfo (@"c:\logs")} }; Blah b = new Blah (); Type blahType = b.GetType (); for...

  18. 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 Name property is marked with the virtual keyword. protected new string _name = "Derived class"; We ...

  19. How to customize property names and values with System.Text.Json

    To set the name of individual properties, use the [JsonPropertyName] attribute. Here's an example type to serialize and resulting JSON: C# public class WeatherForecastWithPropertyNameAttribute { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string?

  20. c#

    How do I set a static property of a class using reflection when I only have its string name of the property? For instance I have: Stack Overflow. About; Products For Teams; ... C# Reflection: Fastest Way to Update a Property Value? 0. Assign object attribute to a String variable in SAP using c#-1. Change property value. 0.

  21. Create a form in Word that users can complete or print

    Add content to the form. Go to the Developer tab Controls section where you can choose controls to add to your document or form. Hover over any icon therein to see what control type it represents. The various control types are described below. You can set properties on a control once it has been inserted.

  22. Named and Optional Arguments

    22 contributors Feedback In this article Named arguments Optional arguments COM interfaces Overload resolution C# language specification Named arguments enable you to specify an argument for a parameter by matching the argument with its name rather than with its position in the parameter list.