C# Type GetProperty(String, BindingFlags)
Description
Type GetProperty(String, BindingFlags)
searches for
the specified property, using the specified binding constraints.
Syntax
Type.GetProperty(String, BindingFlags)
has the following syntax.
public PropertyInfo GetProperty(
string name,
BindingFlags bindingAttr
)
Parameters
Type.GetProperty(String, BindingFlags)
has the following parameters.
name
- The string containing the name of the property to get.bindingAttr
- A bitmask comprised of one or more BindingFlags that specify how the search is conducted.bindingAttr
- -or-bindingAttr
- Zero, to return null.
Returns
Type.GetProperty(String, BindingFlags)
method returns An object representing the property that matches the specified requirements,
if found; otherwise, null.
Example
The following example retrieves the type of a user-defined class, retrieves a property of that class and displays the property name in accordance with the specified binding constraints.
using System;/*from www. j a v a2 s . co 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", BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine("{0} is a property of MyClass.", myPropInfo.Name);
}
catch(NullReferenceException e)
{
Console.WriteLine("MyProperty does not exist in MyClass." +e.Message);
}
}
}
The code above generates the following result.