Search code examples
c#reflectionderived-classbase-class

modifying derived class values from base class


Is it possible to have a method in a base class to modify a derived class' properties? I was thinking something like this:

public class baseclass
{
  public void changeProperties(string propertyName, string newValue)
  {
    try
    {
      this.propertyName = newValue;
    }
    catch
    {
      throw new NullReferenceException("Property doesn't exist!");
    }
  }
}

Solution

  • You can solve your problem via reflection, because this reference's type will be equal actual type, i.e. type of derived class:

    Solution:

    public class baseclass
    {
        public void changeProperties(string propertyName, object newValue)
        {            
            var prop = GetType().GetProperty(propertyName);
            if (prop == null)
                throw new NullReferenceException("Property doesn't exist!");
            else
                prop.SetValue(this, newValue);
        }
    }
    

    Implementation:

    public class Test : baseclass
    {
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var test = new Test();
            test.changeProperties("Age", 2);
        }
    }