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.
Use PropertyInfo. PropertyType to get the type of the property. Show activity on this post.
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.
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.
< 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.
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(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With