code_junkie

Virtual member call in a constructor

Nov 11th, 2011
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. namespace Demo
  2. {
  3. class A
  4. {
  5. public A()
  6. {
  7. System.Console.WriteLine("This is a {0},", this.GetType());
  8. }
  9. }
  10.  
  11. class B : A
  12. {
  13. }
  14.  
  15. // . . .
  16.  
  17. B b = new B(); // Output: "This is a Demo.B"
  18. }
  19.  
  20. class Parent
  21. {
  22. public Parent()
  23. {
  24. DoSomething();
  25. }
  26. protected virtual void DoSomething() {};
  27. }
  28.  
  29. class Child : Parent
  30. {
  31. private string foo;
  32. public Child() { foo = "HELLO"; }
  33. protected override void DoSomething()
  34. {
  35. Console.WriteLine(foo.ToLower());
  36. }
  37. }
  38.  
  39. class B
  40. {
  41. protected virtual void Foo() { }
  42. }
  43.  
  44. class A : B
  45. {
  46. public A()
  47. {
  48. Foo(); // warning here
  49. }
  50. }
  51.  
  52. sealed class A : B
  53. {
  54. public A()
  55. {
  56. Foo(); // no warning
  57. }
  58. }
  59.  
  60. class A : B
  61. {
  62. public A()
  63. {
  64. Foo(); // no warning
  65. }
  66.  
  67. protected sealed override void Foo()
  68. {
  69. base.Foo();
  70. }
  71. }
Add Comment
Please, Sign In to add comment