Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

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

Sets the value of the property 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 value for this property.

index
Type: System.Object[]

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

Implements

_PropertyInfo.SetValue(Object, Object, Object[])

ExceptionCondition
ArgumentException

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

-or-

The property's set accessor is not found.

TargetException

The object does not match the target type.

-or-

The 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

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.

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.

NoteNote:

Starting with the .NET Framework version 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 version 3.5. For more information, see .NET Framework 3.5 Architecture.

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'
 */

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Community Additions

Show:
© 2014 Microsoft