0

In C#, is it possible to check if a Property has a Setter that references another object at runtime?

Here is some code:

private PropertyChanged _propertyChanged;
public string PropertyChangedName
{
    get
    {
        return _propertyChanged.Name;
    }
    set
    {
        _propertyChanged.Name = value;
    }
}

In the above code, the PropertyChangedName is referenced as part of the PropertyChanged object. When setting the PropertyChangedName, the _propertyChanged.Name is set.

Here is some code where the PropertyChangedName is not referenced as part of the PropertyChanged object:

private string _propertyChangedName;
public string PropertyChangedName
{
    get
    {
        return _propertyChangedName;
    }
    set
    {
        _propertyChangedName = value;
    }
}
Simon
  • 7,991
  • 21
  • 83
  • 163

3 Answers3

0

I am not sure this is the best way, however, it might help you:

// store the current state:
var valuesbefore = new List<object>();
foreach (var r in this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic))
    valuesbefore.Add(r.GetValue(this));

// change the value the specified property
PropertyChangedName = PropertyChangedName + "a"; 

//get the new state of the class:
var valuesnow = new List<object>();
foreach (var r in this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic))
    valuesnow.Add(r.GetValue(this));

// check for any change
bool equal = valuesbefore.SequenceEqual(valuesnow);

If equal is false, it means that you are dealing with a case in which the setter changes the value of private field. Note that special care is required when dealing with types other than string, int, etc.

rmojab63
  • 3,513
  • 1
  • 15
  • 28
  • Is it possible to perform the code you have posted at runtime? – Simon Feb 07 '17 at 03:11
  • Did you encounter any problems? Note that the logic is easy: Save a copy of the class, change the property, compare it with the saved copy and see what happened. – rmojab63 Feb 07 '17 at 03:27
  • Your code is not viable as the code needs to be performed on many objects at runtime, without saving a copy of the class. Is there another possible way? – Simon Feb 07 '17 at 03:40
  • I forgot to add _.GetValue(this)_ of the FiledInfo. I corrected it. – rmojab63 Feb 07 '17 at 03:53
  • Don't forget to replace _this.GetType()_ with the type you are dealing with. – rmojab63 Feb 07 '17 at 03:56
0

You could implement INotifyPropertyChanged and subscribe to it.

John Wu
  • 50,556
  • 8
  • 44
  • 80
0

This is a really tricky question. The System.Reflection library in .NET allows you to observe the class signatures (Types, Fields, Methods, etc), invoke them, and get their values; but not see within their body.

Read through the answers in this question for some options to inspect the contents of methods. (a Property is just a method -- two if you have both get and set)

Community
  • 1
  • 1
NPras
  • 3,135
  • 15
  • 29