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!");
}
}
}
You can solve your problem via reflection, because this
reference's type will be equal actual type, i.e. type of derived class:
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);
}
}