Reflection: get fieldInfoInfo from PropertyInfo
I am doing dynamic code generation using Reflection and I am facing a situation where I need to get the backing field of a property (if any) in order to use its FieldInfo object.
Now I know that you can use
.IsDefined(typeof(CompilerGeneratedAttribute), false);
in FieldInfo to see if it was autogenerated, so I am assuming there is a similar function for properties that automatically generate fields?
Cheers, Ed
a source to share
Methods get_
and set_
for properties are also applied to them CompilerGeneratedAttributed
. Despite not being tightly coupled through attributes, there is a naming convention used for fields supporting the auto property:
public string Foo { get; set;}
Produces a member private string <Foo>k__BackingField
( <
and >
are part of the name here, since they are legal in IL but not in C #, they have nothing to do with generics).
As an example, this will get a list of all auto properties in a class along with their backing fields:
t.GetProperties().Where(p =>
(p.GetGetMethod() ?? p.GetSetMethod()).IsDefined(typeof(CompilerGeneratedAttribute), false))
.Select(p => new
{
Property = p,
Field = t.GetField(string.Format("<{0}>k__BackingField", p.Name),
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance)
});
a source to share
There is no built-in method for this, since having a property does not necessarily guarantee that there is a backing field.
I found this article that explains one way to do this. This involves getting the IL of the setter object and parsing it, looking for evidence of a set field.
a source to share
Andrew is right.
Actually, a property is just a "pointer" to methods, usually getters / setters, when generated by Visual Studio or another high-level language (in most cases).
Parsing a setter isn't easy. And since internal setters are just another vanilla method, they can use more than one field, or not use at all, or even call other methods. Maybe you can come up with a solution for common scenarios, but you need to parse the IL bytecode.
a source to share