Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are GetField, SetField, GetProperty and SetProperty in BindingFlags enumeration?

I have no idea what these are for. The documentation is not very clear:

GetField Specifies that the value of the specified field should be returned.

SetField Specifies that the value of the specified field should be set.

GetProperty Specifies that the value of the specified property should be returned.

SetProperty Specifies that the value of the specified property should be set. For COM properties, specifying this binding flag is equivalent to specifying PutDispProperty and PutRefDispProperty.

If I specify them in BindingFlags enumeration, what should they return? I thought it has to do with properties and fields of a type, but this simple test says no:

class Base
{
    int i;
    int I { get; set; }

    void Do()
    {

    }
}

print typeof(Base).GetMembers(BindingFlags.GetField 
                              | BindingFlags.Instance 
                              | BindingFlags.NonPublic);

// Int32 get_I()
// Void set_I(Int32)
// Void Do()
// Void Finalize()
// System.Object MemberwiseClone()
// Int32 I
// Int32 i
// Int32 <I>k__BackingField

The same set is returned for SetField, GetProperty and SetProperty.

like image 557
nawfal Avatar asked May 12 '13 06:05

nawfal


People also ask

What are BindingFlags?

This binding flag is used for methods with parameters that have default values and methods with variable arguments (varargs). This flag should only be used with InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).

What is BindingFlags instance in C#?

Specifies flags that control binding and the way in which the search for members and types is conducted by reflection. This enumeration supports a bitwise combination of its member values.


1 Answers

All of these are not needed to enumerate but rather to access properties properly. For example, to set a value of the property on given instance, you need SetProperty flag.

 Base b;

 typeof(Base).InvokeMember( "I", 
     BindingFlags.SetProperty|BindingFlags.Public|BindingFlags.Instance,
     ...,
     b, new object[] { newvalue } );

but to get the value of this property, you would need to use the GetProperty: flag.

 Base b;

 int val = (int)typeof(Base).InvokeMember( "I", 
     BindingFlags.GetProperty|BindingFlags.Public|BindingFlags.Instance,
     ...,
     b, null);
like image 109
Wiktor Zychla Avatar answered Sep 21 '22 11:09

Wiktor Zychla