So in my case i am doing discovery of the structure of a class using reflection. I need to be able to find out if a property is an auto-implemented property by the PropertyInfo object. I assume that the reflection API does not expose such functionality because auto-properties are C# dependent, but is there any workaround to get this information?
views:
162answers:
1
+2
A:
You could check to see if the get
or set
method is marked with the CompilerGenerated
attribute. You could then combine that with looking for a private field that is marked with the CompilerGenerated
attribute containing the name of the property and the string "BackingField"
.
Perhaps:
public static bool MightBeCouldBeMaybeAutoGeneratedInstanceProperty(
this PropertyInfo info
) {
bool mightBe = info.GetGetMethod()
.GetCustomAttributes(
typeof(CompilerGeneratedAttribute),
true
)
.Any();
if (!mightBe) {
return false;
}
bool maybe = info.DeclaringType
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.Name.Contains(info.Name))
.Where(f => f.Name.Contains("BackingField"))
.Where(
f => f.GetCustomAttributes(
typeof(CompilerGeneratedAttribute),
true
).Any()
)
.Any();
return maybe;
}
It's not fool proof, quite brittle and probably not portable to, say, Mono.
Jason
2010-02-05 20:51:34
Thanks a lot Jason, the Reflector told me the same in the meantime:) Should have thought of it earlier.
Zoki
2010-02-05 21:02:28
@3o4eTo: Just be forewarned that this not fool proof, brittle and possibly not portable to Mono.
Jason
2010-02-05 21:07:34