C# Type GetProperty(String)

Description

Type GetProperty(String) searches for the public property with the specified name.

Syntax

Type.GetProperty(String) has the following syntax.


public PropertyInfo GetProperty(
  string name
)

Parameters

Type.GetProperty(String) has the following parameters.

  • name - The string containing the name of the public property to get.

Returns

Type.GetProperty(String) method returns An object representing the public property with the specified name, if found; otherwise, null.

Example

The following example retrieves the Type object of a user-defined class, retrieves a property of that class, and displays the property name.


using System;/*from  www.  ja  v a2 s .  c  o  m*/
using System.Reflection;

class MyClass
{
    private int myProperty;
    // Declare MyProperty. 
    public int MyProperty
    {
        get
        {
            return myProperty;
        }
        set
        {
            myProperty=value;
        }
    }
}
public class MyTypeClass
{
    public static void Main(string[] args)
    {
        try
        {
            Type myType=typeof(MyClass);       
            PropertyInfo myPropInfo = myType.GetProperty("MyProperty");
            Console.WriteLine("The {0} property exists in MyClass.", myPropInfo.Name);
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine("The property does not exist in MyClass." + e.Message);
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version