This is the code:
void Main()
{
Base.Title.Dump("Base"); // displays "Base Title"
Child.Title.Dump("Child"); // displays "Base Title"
Base baseClass = new Base();
Base childClass = new Child(); // "InvalidOperationException" would be thrown
}
class Base {
public const string Title = "Base Title";
public string ClassTitle { get; set; }
public Base() {
Type type = this.GetType();
type.GetFields()
.First(item => item.Name == "Title")
.GetValue(this).Dump();
}
}
class Child : Base {
private new const string Title = "Child Title";
}
An “InvalidOperationException” exception is thrown in Base constructor.
If you want the derived class Title, you need to either make the child class’ Title public
or rudely crack open its private members with something like this:
If you want the base class Title, then your line:
is getting the derived type when you want the base type.
Try this instead: