I'm trying to call derived methods in a base constructor. I'd hoped the code below would result in a print of "Hello Derived" (specifically due to calling ParseData
as a method of this
.
using System;
public class Program
{
public static void Main()
{
Derived a = new Derived("Hello");
}
public class Base
{
public Base(string s)
{
this.ParseData(s);
}
protected void ParseData(string s)
{
Console.WriteLine(s+ " Base");
}
}
public class Derived : Base
{
public Derived(string s) : base(s){}
new private void ParseData(string s)
{
Console.WriteLine(s + " Derived");
}
}
}
I understand from the answer to this previous question why it doesn't work as I'd hoped it would - but can anyone provide suggestions of how best to implement my desired effect without resorting to having to call ParseData
in my calling code after construction is complete every time this object in constructed - as below - if at all possible. (I'm likely to have a lot of different derived classes to do this on...)
Thanks!
using System;
public class Program
{
public static void Main()
{
string s = "Hello";
Derived a = new Derived(s);
a.ParseData(s);
}
public class Base
{
public Base(string s)
{}
protected void ParseData(string s)
{
Console.WriteLine(s+ " Base");
}
}
public class Derived : Base
{
public Derived(string s) : base(s){}
new private void ParseData(string s)
{
Console.WriteLine(s + " Derived");
}
}
}