Call method from a parent class and use child class properties

Actual call:

ChildClass classCall=new ChildClass();
classCall.FullName="test name";
string returnName=classCall.GetName();

Parent class with method:

public class BaseClass
{
    public string GetName()
    {
        // I can request the value of the property like this.
        return this.GetType().GetProperty("FullName")
                   .GetValue(this, null).ToString();
    }
}

Child class:

public partial class ChildClass : BaseClass
{
    public string FullName;
    public int Marks;
}

Question: How can I avoid hardcoding the property name, i.e. GetProperty("FullName"). I don't want to hardcode the property name, rather use some other approach and use it in parent method?

Jon Skeet
people
quotationmark

Firstly, I'd suggest avoiding using public fields - use properties if you want to make state public. (You're asking for a property in your reflection call, but your derived class declares a field...)

At that point, you can make FullName an abstract property in the base class, and allow each derived class to implement it however they want - but you can still call it from the base class.

On the other hand, if every derived class is going to have to implement it, why not just pass it into the base class's constructor? Either the class makes sense without a FullName or it doesn't - your current code will break if there isn't a FullName field, so why not have it in the base class to start with?

people

See more on this question at Stackoverflow