PropertyInfo.GetValue Method

Definition

Returns the property value of a specified object.

Overloads

GetValue(Object)

Returns the property value of a specified object.

GetValue(Object, Object[])

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

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

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

GetValue(Object)

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

Returns the property value of a specified object.

C#
public object GetValue (object obj);
C#
public object? GetValue (object? obj);

Parameters

obj
Object

The object whose property value will be returned.

Returns

The property value of the specified object.

Examples

The following example defines a Planet class that has two properties: Name, the name of the planet; and Distance, the planet's distance from Earth. The example instantiates a Planet object that represents the planet Jupiter and passes it to a GetPropertyValues method that displays information about the properties and uses the GetValue method to get the value of each Planet property.

C#
using System;
using System.Reflection;

public class Planet
{
   private String planetName;
   private Double distanceFromEarth;
   
   public Planet(String name, Double distance)
   {
      planetName = name;
      distanceFromEarth = distance;
   } 

   public String Name
   { get { return planetName; } }
   
   public Double Distance 
   { get { return distanceFromEarth; }
     set { distanceFromEarth = value; } }
}

public class Example
{
   public static void Main()
   {
      Planet jupiter = new Planet("Jupiter", 3.65e08);
      GetPropertyValues(jupiter);
   }
   
   private static void GetPropertyValues(Object obj)
   {
      Type t = obj.GetType();
      Console.WriteLine("Type is: {0}", t.Name);
      PropertyInfo[] props = t.GetProperties();
      Console.WriteLine("Properties (N = {0}):", 
                        props.Length);
      foreach (var prop in props)
         if (prop.GetIndexParameters().Length == 0)
            Console.WriteLine("   {0} ({1}): {2}", prop.Name,
                              prop.PropertyType.Name,
                              prop.GetValue(obj));
         else
            Console.WriteLine("   {0} ({1}): <Indexed>", prop.Name,
                              prop.PropertyType.Name);
   }
}
// The example displays the following output:
//       Type is: Planet
//       Properties (N = 2):
//          Name (String): Jupiter
//          Distance (Double): 365000000

Remarks

You call the GetValue(Object) overload to retrieve the value of a non-indexed property; if you try to retrieve the value of an indexed property, the method throws a TargetParameterCountException exception. You can determine whether a property is indexed or not by calling the GetIndexParameters method. If the length of the returned ParameterInfo array is zero, the property is not indexed.

This is a convenience method that provides an implementation for the abstract GetValue(Object, BindingFlags, Binder, Object[], CultureInfo) method with the BindingFlags parameter set to BindingFlags.Default, the Binder set to null, the object array of index values set to null, and the CultureInfo set to null.

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

GetValue(Object, Object[])

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

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

C#
public virtual object GetValue (object obj, object[] index);
C#
public virtual object? GetValue (object? obj, object?[]? index);

Parameters

obj
Object

The object whose property value will be returned.

index
Object[]

Optional index values for indexed properties. The indexes of indexed properties are zero-based. This value should be null for non-indexed properties.

Returns

The property value of the specified object.

Implements

Exceptions

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

-or-

The property's get accessor is not found.

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 retrieving 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 shows how to get the value of an indexed property. The String.Chars[] property is the default property (the indexer in C#) of the String class.

C#
using System;
using System.Reflection;

class Example
{
    public static void Main()
    {
        string test = "abcdefghijklmnopqrstuvwxyz";

        // Get a PropertyInfo object representing the Chars property.
        PropertyInfo pinfo = typeof(string).GetProperty("Chars");

        // Show the first, seventh, and last letters
        ShowIndividualCharacters(pinfo, test, 0, 6, test.Length - 1);

        // Show the complete string.
        Console.Write("The entire string: ");
        for (int x = 0; x < test.Length; x++)
        {
            Console.Write(pinfo.GetValue(test, new Object[] {x}));
        }
        Console.WriteLine();
    }

    static void ShowIndividualCharacters(PropertyInfo pinfo, 
                                         object value,
                                         params int[] indexes)
    {
       foreach (var index in indexes) 
          Console.WriteLine("Character in position {0,2}: '{1}'",
                            index, pinfo.GetValue(value, new object[] { index }));
       Console.WriteLine();                          
    }                                      
}
// The example displays the following output:
//    Character in position  0: 'a'
//    Character in position  6: 'g'
//    Character in position 25: 'z'
//    
//    The entire string: abcdefghijklmnopqrstuvwxyz

Remarks

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 provides an implementation for the abstract GetValue method with a BindingFlags parameter of Default, the Binder set to null, and the CultureInfo set to null.

Because static properties belong to the type, not individual objects, get static properties by passing null as the object argument. For example, use the following code to get the static CurrentCulture property of CultureInfo :

C#
PropertyInfo CurCultProp =
    (typeof(CultureInfo)).GetProperty("CurrentCulture");
Console.WriteLine("CurrCult: " +
    CurCultProp.GetValue(null,null));

To use the GetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetValue 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

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

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

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

C#
public abstract object? GetValue (object? obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? index, System.Globalization.CultureInfo? culture);
C#
public abstract object GetValue (object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] index, System.Globalization.CultureInfo culture);

Parameters

obj
Object

The object whose property value will be returned.

invokeAttr
BindingFlags

A bitwise combination of the following enumeration members that specify the invocation attribute: InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty, and 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.

Returns

The property value of the specified object.

Implements

Exceptions

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

-or-

The property's get accessor is not found.

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 retrieving 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

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

Because static properties belong to the type, not individual objects, get static properties by passing null as the object argument. For example, use the following code to get the static CurrentCulture property of CultureInfo :

C#
PropertyInfo CurCultProp =
       (typeof(CultureInfo)).GetProperty("CurrentCulture");
Console.WriteLine("CurrCult: " +
       CurCultProp.GetValue(null,null));

To use the GetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetValue 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.

See also

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