Advertisement
atsukanrock

Overriding method is invoked by event

Nov 1st, 2012
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.93 KB | None | 0 0
  1. // Program.cs
  2. using System;
  3.  
  4. namespace ConsoleApplication1
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             var instance = new DerivedClass();
  11.             instance.Init();
  12.             instance.DoSomething(); // outputs "DerivedClass"
  13.         }
  14.     }
  15.  
  16.     class EventSource
  17.     {
  18.         public event EventHandler SomeEvent;
  19.  
  20.         public void DoSomething()
  21.         {
  22.             if (this.SomeEvent != null) this.SomeEvent(this, EventArgs.Empty);
  23.         }
  24.     }
  25.  
  26.     class BaseClass
  27.     {
  28.         private readonly EventSource _source = new EventSource();
  29.  
  30.         public void Init()
  31.         {
  32.             _source.SomeEvent += _source_SomeEvent;
  33.         }
  34.  
  35.         protected virtual void _source_SomeEvent(object sender, EventArgs e)
  36.         {
  37.             Console.WriteLine("BaseClass");
  38.         }
  39.  
  40.         public void DoSomething()
  41.         {
  42.             _source.DoSomething();
  43.         }
  44.     }
  45.  
  46.     class DerivedClass : BaseClass
  47.     {
  48.         protected override void _source_SomeEvent(object sender, EventArgs e)
  49.         {
  50.             Console.WriteLine("DerivedClass");
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement