code_junkie

C# calling overridden subclass methods without knowledge that it's a subclass instance

Nov 13th, 2011
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. Class Foo
  2. {
  3. public virtual printMe()
  4. {
  5. Console.Writeline("FOO");
  6. }
  7. }
  8.  
  9. Class Bar : Foo
  10. {
  11. public override printMe()
  12. {
  13. Console.Writeline("BAR");
  14. }
  15. }
  16.  
  17. List<Foo> list = new List<Foo>();
  18. // then populate this list with various 'Bar' and other overriden Foos
  19.  
  20. foreach (Foo foo in list)
  21. {
  22. foo.printMe(); // prints FOO.. Would like it to print BAR
  23. }
  24.  
  25. class Foo
  26. {
  27. public virtual void virtualPrintMe()
  28. {
  29. nonVirtualPrintMe();
  30. }
  31.  
  32. public void nonVirtualPrintMe()
  33. {
  34. Console.Writeline("FOO");
  35. }
  36. }
  37.  
  38. class Bar : Foo
  39. {
  40. public override void virtualPrintMe()
  41. {
  42. Console.Writeline("BAR");
  43. }
  44. }
  45.  
  46. List<Foo> list = new List<Foo>();
  47. // then populate this list with various 'Bar' and other overriden Foos
  48.  
  49. foreach (Foo foo in list)
  50. {
  51. foo.virtualPrintMe(); // prints BAR or FOO
  52. foo.nonVirtualPrintMe(); // always prints FOO
  53. }
  54.  
  55. foo.printMe(); // prints FOO.. Would like it to print BAR
  56.  
  57. (Foo)foo.printMe(); // foo can be any derived class of Foo.
Add Comment
Please, Sign In to add comment