I have an abstract class (Parent) with a function called funcA. Parent has 4 childern and the user needs to choose which one to access. What I need to do is to access the overrided method funcA in the child subclass that was chosen by the user and activate it.
Parent:
public abstract class Parent
{
public string PropA {get; set;}
public string PropB {get; set;}
public DateTime PropC {get; set;}
public DateTime PropD {get; set;}
public abstract void FuncA();
}
Child:
public class ChildA: Parent
{
public string PropE {get; set;}
public string PropF {get; set;}
public override void FuncA()
{
// Some Code
}
}
Main:
public static void Main(string[] args)
{
Console.WriteLine("Enter the type of child: ");
string type = Console.Readline();
// I need to identify which child is type, access that child's FuncA and
// run it.
}
The string type is validated as an existing child. There is no way the user enters a type that does not exist.
If you're always calling the abstract method you can just cast the object to a Parent
and call the method in a type-safe manner:
Type t = Type.GetType("ChildA");
Parent p = Activator.CreateInstance(t) as Parent;
p.FuncA();
Since FuncA
is virtual, the most derived implementation will be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With