Search code examples
c#propertiesbindingflags

Filter "own members" with BindingFlags


I got the following code :

public class PluginShape : INotifyPropertyChanged
{
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set
        {
            _Name = value;
            RaisePropertyChanged("Name");
        }
    }

    #region Implement INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

public class SpeedGenerator : PluginShape
{
    private int _SpeedValue;
    public int SpeedValue
    {
        get { return _SpeedValue; }
        set
        {
            _SpeedValue = value;
            RaisePropertyChanged("SpeedValue");
        }
    }

    public SpeedGenerator()
    {
        Name = "DefaultName";
    }
}

Then I'd like to filter the properties so that I only get the SpeedValue property. I thought the following code will be ok, but it doesn't work :

var props = obj.GetType().GetProperties();
var filteredProps = obj.GetType().GetProperties(BindingFlags.DeclaredOnly);

in "props" I got both SpeedValue and Name properties but in "filteredProps" I got nothing... Any help please ?


Solution

  • According to the documentation,

    You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

    Specify BindingFlags.Public to include public properties in the search.

    Thus, the following should do what you want:

    var filteredProps = obj.GetType().GetProperties(BindingFlags.Instance | 
                                                    BindingFlags.Public |
                                                    BindingFlags.DeclaredOnly);