fork download
  1. using System;
  2.  
  3. public abstract class BaseClass {
  4. private string m_Name;
  5.  
  6. protected BaseClass(string name) {
  7. m_Name = name;
  8. }
  9.  
  10. public void Output()
  11. {
  12. Console.WriteLine("The class is: " + this.GetType());
  13. Console.WriteLine("The name is: " + m_Name);
  14. }
  15. }
  16.  
  17. public class DerivedA : BaseClass {
  18. public DerivedA(string name) : base(name) {}
  19. }
  20.  
  21. public class DerivedB : BaseClass {
  22. public DerivedB(string name) : base(name) {}
  23. }
  24.  
  25. public static class MyStaticClass {
  26. public static T Create<T>(string name)
  27. where T : BaseClass
  28. {
  29. return (T)Activator.CreateInstance(typeof(T), new[] { name });
  30. }
  31. }
  32.  
  33. class Test {
  34. static void Main() {
  35. var a = MyStaticClass.Create<DerivedA>("derived a");
  36. var b = MyStaticClass.Create<DerivedB>("derived b");
  37.  
  38. a.Output();
  39. b.Output();
  40. }
  41. }
Success #stdin #stdout 0.03s 33832KB
stdin
Standard input is empty
stdout
The class is: DerivedA
The name is: derived a
The class is: DerivedB
The name is: derived b