0

I did follow the following posts' suggestions

  1. Reflecting over all properties of an interface, including inherited ones?
  2. How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)
  3. Using GetProperties() with BindingFlags.DeclaredOnly in .NET Reflection

and modified my test to include the bindingflags as seen below.

Goal: my end goal is to test if the retrieved property is readOnly.

Issue: ChildClass/Inherited class property does not even show up on reflection.

Test to check if property exists - fails.

On GetProperties(BindingFlags.FlattenHiearchy) returns only one property which is the Result which is the parent class's property

//My failing test
Assert.NotNull(typeof(ChildClass).GetProperty("Id",BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly));

//My Alternate version which still fails
Assert.NotNull(typeof(ChildClass).GetProperty("Id",BindingFlags.FlattenHierarchy));

// My class structure against which my test is running.
class ChildClass:BaseClass<MyCustomObject>
{
   public ChildClass (Guid id)
    {
        Id = id;
    }

    public readonly Guid Id;
}

class BaseClass<T>:IMyInterFace<T>
{
     public T Result { get; private set; }
}

public interface IMyInterFace<T>
{
    T Result { get; }

}

EDIT 9/14/2016 I apologize I missed the fact that I actually did know or understand I can Assert.NotNull if i say GetField - but that wouldnt help me achieve the end goal - to check if it is readonly - I am now unsure as to if this is even possible can someone confirm? thanks!.

Community
  • 1
  • 1
Jaya
  • 3,721
  • 4
  • 32
  • 48

1 Answers1

3

public readonly Guid Id is a field, not a property. Use the GetField method instead:

typeof(ChildClass).GetField("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

You can check to see if it is readonly by looking at the IsInitOnly property of the FieldInfo class.

var result = typeof(ChildClass).GetField("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Assert.IsTrue(result.IsInitOnly);
Will Ray
  • 10,621
  • 3
  • 46
  • 61
  • Sure, this would work, but how would I achieve my end there that is stated - meaning I would want to check if it is read only - is that not possible given that it is a field? – Jaya Sep 15 '16 at 00:20
  • @JS_GodBlessAll In the second part of my answer I stated that you can check by looking at the `IsInitOnly` property from result. Did that work for you? – Will Ray Sep 15 '16 at 00:57
  • ... As in `var result = typeof(ChildClass).GetField(/*all that stuff*/)` then `Assert.IsTrue(result.IsInitOnly)` – Will Ray Sep 15 '16 at 01:14