PropertyInfo.SetValue Method

Definition

Sets the property value for a specified object.

Overloads

SetValue(Object, Object)

Sets the property value of a specified object.

SetValue(Object, Object, Object[])

Sets the property value of a specified object with optional index values for index properties.

SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)

When overridden in a derived class, sets the property value for a specified object that has the specified binding, index, and culture-specific information.

SetValue(Object, Object)

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

Sets the property value of a specified object.

public void SetValue (object obj, object value);
public void SetValue (object? obj, object? value);

Parameters

obj
Object

The object whose property value will be set.

value
Object

The new property value.

Exceptions

The property's set accessor is not found.

-or-

value cannot be converted to the type of PropertyType.

The type of obj does not match the target type, or a property is an instance property but obj is null.

Note: In .NET for Windows Store apps or the Portable Class Library, catch Exception instead.

There was an illegal attempt to access a private or protected method inside a class.

Note: In .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

An error occurred while setting the property value. The InnerException property indicates the reason for the error.

Examples

The following example declares a class named Example with one static (Shared in Visual Basic) and one instance property. The example uses the SetValue(Object, Object) method to change the original property values and displays the original and final values.

using System;
using System.Reflection;

class Example
{
    private static int _staticProperty = 41;
    private int _instanceProperty = 42;

    // Declare a public static property.
    public static int StaticProperty
    {
        get { return _staticProperty; }
        set { _staticProperty = value; }
    }

    // Declare a public instance property.
    public int InstanceProperty
    {
        get { return _instanceProperty; }
        set { _instanceProperty = value; }
    }

    public static void Main()
    {
        Console.WriteLine("Initial value of static property: {0}",
            Example.StaticProperty);

        // Get a type object that represents the Example type.
        Type examType = typeof(Example);

        // Change the static property value.
        PropertyInfo piShared = examType.GetProperty("StaticProperty");
        piShared.SetValue(null, 76);

        Console.WriteLine("New value of static property: {0}",
                          Example.StaticProperty);

        // Create an instance of the Example class.
        Example exam = new Example();

        Console.WriteLine("\nInitial value of instance property: {0}",
                          exam.InstanceProperty);

        // Change the instance property value.
        PropertyInfo piInstance = examType.GetProperty("InstanceProperty");
        piInstance.SetValue(exam, 37);

        Console.WriteLine("New value of instance property: {0}",
                          exam.InstanceProperty);
    }
}
// The example displays the following output:
//       Initial value of static property: 41
//       New value of static property: 76
//
//       Initial value of instance property: 42
//       New value of instance property: 37

Remarks

The SetValue(Object, Object) overload sets the value of a non-indexed property. To determine whether a property is indexed, call the GetIndexParameters method. If the resulting array has 0 (zero) elements, the property is not indexed. To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload.

If the property type of this PropertyInfo object is a value type and value is null, the property will be set to the default value for that type.

This is a convenience method that calls the runtime implementation of the abstract SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) method, specifying BindingFlags.Default for the BindingFlags parameter, null for Binder, null for Object[], and null for CultureInfo.

To use the SetValue method, first get a Type object that represents the class. From the Type, get the PropertyInfo object. From the PropertyInfo object, call the SetValue method.

Note

Starting with .NET Framework 2.0, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (See Security Considerations for Reflection.) To use this functionality, your application should target .NET Framework 3.5 or later.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

SetValue(Object, Object, Object[])

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

Sets the property value of a specified object with optional index values for index properties.

public virtual void SetValue (object obj, object value, object[] index);
public virtual void SetValue (object? obj, object? value, object?[]? index);

Parameters

obj
Object

The object whose property value will be set.

value
Object

The new property value.

index
Object[]

Optional index values for indexed properties. This value should be null for non-indexed properties.

Implements

Exceptions

The index array does not contain the type of arguments needed.

-or-

The property's set accessor is not found.

-or-

value cannot be converted to the type of PropertyType.

The object does not match the target type, or a property is an instance property but obj is null.

Note: In .NET for Windows Store apps or the Portable Class Library, catch Exception instead.

The number of parameters in index does not match the number of parameters the indexed property takes.

There was an illegal attempt to access a private or protected method inside a class.

Note: In .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

An error occurred while setting the property value. For example, an index value specified for an indexed property is out of range. The InnerException property indicates the reason for the error.

Examples

The following example defines a class named TestClass that has a read-write property named Caption. It displays the default value of the Caption property, calls the SetValue method to change the property value, and displays the result.

using System;
using System.Reflection;

// Define a class with a property.
public class TestClass
{
    private string caption = "A Default caption";
    public string Caption
    {
        get { return caption; }
        set
        {
            if (caption != value)
            {
                caption = value;
            }
        }
    }
}

class TestPropertyInfo
{
    public static void Main()
    {
        TestClass t = new TestClass();

        // Get the type and PropertyInfo.
        Type myType = t.GetType();
        PropertyInfo pinfo = myType.GetProperty("Caption");

        // Display the property value, using the GetValue method.
        Console.WriteLine("\nGetValue: " + pinfo.GetValue(t, null));

        // Use the SetValue method to change the caption.
        pinfo.SetValue(t, "This caption has been changed.", null);

        //  Display the caption again.
        Console.WriteLine("GetValue: " + pinfo.GetValue(t, null));

        Console.WriteLine("\nPress the Enter key to continue.");
        Console.ReadLine();
    }
}

/*
This example produces the following output:

GetValue: A Default caption
GetValue: This caption has been changed

Press the Enter key to continue.
*/

Note that, because the Caption property is not a parameter array, the index argument is null.

The following example declares a class named Example with three properties: a static property (Shared in Visual Basic), an instance property, and an indexed instance property. The example uses the SetValue method to change the default values of the properties and displays the original and final values.

The name that is used to search for an indexed instance property with reflection is different depending on the language and on attributes applied to the property.

  • In Visual Basic, the property name is always used to search for the property with reflection. You can use the Default keyword to make the property a default indexed property, in which case you can omit the name when accessing the property, as in this example. You can also use the property name.

  • In C#, the indexed instance property is a default property called an indexer, and the name is never used when accessing the property in code. By default, the name of the property is Item, and you must use that name when you search for the property with reflection. You can use the IndexerNameAttribute attribute to give the indexer a different name. In this example, the name is IndexedInstanceProperty.

  • In C++, the default specifier can be used to make an indexed property a default indexed property (class indexer). In that case, the name of the property by default is Item, and you must use that name when you search for the property with reflection, as in this example. You can use the IndexerNameAttribute attribute to give the class indexer a different name in reflection, but you cannot use that name to access the property in code. An indexed property that is not a class indexer is accessed using its name, both in code and in reflection.

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

class Example
{
    private static int _staticProperty = 41;
    public static int StaticProperty
    {
        get
        {
            return _staticProperty;
        }
        set
        {
            _staticProperty = value;
        }
    }

    private int _instanceProperty = 42;
    public int InstanceProperty
    {
        get
        {
            return _instanceProperty;
        }
        set
        {
            _instanceProperty = value;
        }
    }

    private Dictionary<int, string> _indexedInstanceProperty =
        new Dictionary<int, string>();
    // By default, the indexer is named Item, and that name must be used
    // to search for the property. In this example, the indexer is given
    // a different name by using the IndexerNameAttribute attribute.
    [IndexerNameAttribute("IndexedInstanceProperty")]
    public string this[int key]
    {
        get
        {
            string returnValue = null;
            if (_indexedInstanceProperty.TryGetValue(key, out returnValue))
            {
                return returnValue;
            }
            else
            {
                return null;
            }
        }
        set
        {
            if (value == null)
            {
                throw new ArgumentNullException("IndexedInstanceProperty value can be an empty string, but it cannot be null.");
            }
            else
            {
                if (_indexedInstanceProperty.ContainsKey(key))
                {
                    _indexedInstanceProperty[key] = value;
                }
                else
                {
                    _indexedInstanceProperty.Add(key, value);
                }
            }
        }
    }

    public static void Main()
    {
        Console.WriteLine("Initial value of class-level property: {0}",
            Example.StaticProperty);

        PropertyInfo piShared = typeof(Example).GetProperty("StaticProperty");
        piShared.SetValue(null, 76, null);

        Console.WriteLine("Final value of class-level property: {0}",
            Example.StaticProperty);

        Example exam = new Example();

        Console.WriteLine("\nInitial value of instance property: {0}",
            exam.InstanceProperty);

        PropertyInfo piInstance =
            typeof(Example).GetProperty("InstanceProperty");
        piInstance.SetValue(exam, 37, null);

        Console.WriteLine("Final value of instance property: {0}",
            exam.InstanceProperty);

        exam[17] = "String number 17";
        exam[46] = "String number 46";
        exam[9] = "String number 9";

        Console.WriteLine(
            "\nInitial value of indexed instance property(17): '{0}'",
            exam[17]);

        // By default, the indexer is named Item, and that name must be used
        // to search for the property. In this example, the indexer is given
        // a different name by using the IndexerNameAttribute attribute.
        PropertyInfo piIndexedInstance =
            typeof(Example).GetProperty("IndexedInstanceProperty");
        piIndexedInstance.SetValue(
            exam,
            "New value for string number 17",
            new object[] { (int) 17 });

        Console.WriteLine(
            "Final value of indexed instance property(17): '{0}'",
            exam[17]);
    }
}

/* This example produces the following output:

Initial value of class-level property: 41
Final value of class-level property: 76

Initial value of instance property: 42
Final value of instance property: 37

Initial value of indexed instance property(17): 'String number 17'
Final value of indexed instance property(17): 'New value for string number 17'
 */

Remarks

If this PropertyInfo object is a value type and value is null, then the property will be set to the default value for that type.

To determine whether a property is indexed, use the GetIndexParameters method. If the resulting array has 0 (zero) elements, the property is not indexed.

This is a convenience method that calls the runtime implementation of the abstract SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) method, specifying BindingFlags.Default for the BindingFlags parameter, null for Binder, and null for CultureInfo.

To use the SetValue method, first get a Type object that represents the class. From the Type, get the PropertyInfo. From the PropertyInfo, use the SetValue method.

Note

Starting with .NET Framework 2.0, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (See Security Considerations for Reflection.) To use this functionality, your application should target .NET Framework 3.5 or later.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

When overridden in a derived class, sets the property value for a specified object that has the specified binding, index, and culture-specific information.

public abstract void SetValue (object? obj, object? value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? index, System.Globalization.CultureInfo? culture);
public abstract void SetValue (object obj, object value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] index, System.Globalization.CultureInfo culture);

Parameters

obj
Object

The object whose property value will be set.

value
Object

The new property value.

invokeAttr
BindingFlags

A bitwise combination of the following enumeration members that specify the invocation attribute: InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty, or SetProperty. You must specify a suitable invocation attribute. For example, to invoke a static member, set the Static flag.

binder
Binder

An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. If binder is null, the default binder is used.

index
Object[]

Optional index values for indexed properties. This value should be null for non-indexed properties.

culture
CultureInfo

The culture for which the resource is to be localized. If the resource is not localized for this culture, the Parent property will be called successively in search of a match. If this value is null, the culture-specific information is obtained from the CurrentUICulture property.

Implements

Exceptions

The index array does not contain the type of arguments needed.

-or-

The property's set accessor is not found.

-or-

value cannot be converted to the type of PropertyType.

The object does not match the target type, or a property is an instance property but obj is null.

The number of parameters in index does not match the number of parameters the indexed property takes.

There was an illegal attempt to access a private or protected method inside a class.

An error occurred while setting the property value. For example, an index value specified for an indexed property is out of range. The InnerException property indicates the reason for the error.

Remarks

If this PropertyInfo object is a value type and value is null, then the property will be set to the default value for that type.

To determine whether a property is indexed, use the GetIndexParameters method. If the resulting array has 0 (zero) elements, the property is not indexed.

Access restrictions are ignored for fully trusted code. That is, private constructors, methods, fields, and properties can be accessed and invoked via Reflection whenever the code is fully trusted.

To use the SetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the SetValue method.

Note

Starting with .NET Framework 2.0, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (See Security Considerations for Reflection.) To use this functionality, your application should target .NET Framework 3.5 or later.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1