0

Very similar to How to get all public both get and set properties of a type

Suppose I have a simple class:

public class MyClass
{
    private int A {get; set;}
    public int B {get; private set;}
    public int C {get; set;}

    public MyClass() {... sets this.A and this.B}
}

Using reflection I want the sequence of all properties that I can write values to. The following is incorrect:

var allWritableProperties = typeof(MyClass).GetProperties()
    .Where(property => property.CanWrite);
  • Method GetProperties correctly returns only the public properties B and C.
  • Property B has a private Set, so I can't write to it.
  • Yet B CanWrite is true, therefore the Where Function will return B and C.
  • I can only write to C, therefore I want only C

For those who want to know why I want to do this. I have a class with that implements IEquality. I have a unit test that tests whether this is implemented correctly. Recently someone added a property but forgot to change the Equals function. Therefore some different objects were considered to be equal. My unit test should have warned about this.

Therefore I want to change the test such that it changes all public writable properties one by one and checks if Equals returns false. In that case if someone added a public writable property but forgot to use check it in Equals the test would fail.

Community
  • 1
  • 1
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • 1
    Because `CanWrite` doesn't check the `set` accessibility, but just whether it exists. `GetGetMethod()` does only return the setter when it exists _and_ is public, see [duplicate](http://stackoverflow.com/questions/3762456/c-sharp-how-to-check-if-property-setter-is-public). :) So something like `GetProperties().Where(p => p.GetSetMethod(false) != null)`. If that doesn't answer your question I may have misunderstood, feel free to @ping me and I'll reopen as soon as possible. – CodeCaster Sep 18 '15 at 15:51
  • Thanks, should I delete this question? – Harald Coppoolse Sep 21 '15 at 07:46
  • No, you don't have to, really. Differently phrased questions leading to the same answers is a good thing. :) – CodeCaster Sep 21 '15 at 07:50

0 Answers0