Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting to an unknown type's method and run it c#

Tags:

c#

inheritance

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.

like image 786
Einat Lugassy Avatar asked Mar 13 '23 05:03

Einat Lugassy


1 Answers

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.

like image 59
D Stanley Avatar answered Mar 14 '23 18:03

D Stanley