Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the PropertyInfo of a specific property?

Tags:

c#

reflection

I want to get the PropertyInfo for a specific property. I could use:

foreach(PropertyInfo p in typeof(MyObject).GetProperties()) {     if ( p.Name == "MyProperty") { return p } } 

But there must be a way to do something similar to

typeof(MyProperty) as PropertyInfo 

Is there? Or am I stuck doing a type-unsafe string comparison?

Cheers.

like image 338
tenpn Avatar asked Jan 29 '09 12:01

tenpn


People also ask

How do I get a property type from PropertyInfo?

Use PropertyInfo. PropertyType to get the type of the property. Show activity on this post.

How do I find information on a property?

Alternatively, go to the local Tax Assessor's office and give them the owner's name or property address. Property deeds are often available online. Try searching for “Recorder of Deeds,” with the name of the county. Or, go to the county or city office and ask where you can access physical records of property deeds.

How to get properties using Reflection c#?

GetProperties() MethodReflection. PropertyInfo[] GetProperties (); Return Value: This method returns an array of PropertyInfo objects representing all public properties of the current Type or an empty array of type PropertyInfo if the current Type does not have public properties.

What is PropertyInfo in c#?

< Previous Next > The PropertyInfo class discovers the attributes of a property and provides access to property metadata. The PropertyInfo class is very similar to the FieldInfo class and also contains the ability to set the value of the property on an instance.


1 Answers

There is a .NET 3.5 way with lambdas/Expression that doesn't use strings...

using System; using System.Linq.Expressions; using System.Reflection;  class Foo {     public string Bar { get; set; } } static class Program {     static void Main()     {         PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);     } } public static class PropertyHelper<T> {     public static PropertyInfo GetProperty<TValue>(         Expression<Func<T, TValue>> selector)     {         Expression body = selector;         if (body is LambdaExpression)         {             body = ((LambdaExpression)body).Body;         }         switch (body.NodeType)         {             case ExpressionType.MemberAccess:                 return (PropertyInfo)((MemberExpression)body).Member;             default:                 throw new InvalidOperationException();         }     } } 
like image 194
Marc Gravell Avatar answered Dec 06 '22 17:12

Marc Gravell