PropertyInfo.SetValue Method (Object, Object, Object[])

 

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

Namespace:   System.Reflection
Assembly:  mscorlib (in mscorlib.dll)

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

Parameters

obj
Type: System.Object

The object whose property value will be set.

value
Type: System.Object

The new property value.

index
Type: System.Object[]

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

Exception Condition
ArgumentException

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.

TargetException

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

TargetParameterCountException

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

MethodAccessException
System_CAPS_noteNote

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

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

TargetInvocationException

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.

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.

System_CAPS_noteNote

Starting with the .NET Framework 2.0 Service Pack 1, 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 the .NET Framework 3.5 or later.

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 ApplicationException("IndexedInstanceProperty value can be the empty string, but it cannot be Nothing.");
            }
            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'
 */

ReflectionPermission

for accessing non-public members when the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. Associated enumeration: ReflectionPermissionFlag.RestrictedMemberAccess

ReflectionPermission

for accessing non-public members regardless of their grant set. Associated enumeration: ReflectionPermissionFlag.MemberAccess

ReflectionPermission

when invoked late-bound through mechanisms such as Type.InvokeMember. Associated enumeration: ReflectionPermissionFlag.MemberAccess.

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show: