In following code, in the derived class from ArrayList we are using a method as OnChanged().
This class is declared as: protected virtual void OnChanged(EventArgs e)
Question: what is the purpose behind protected and virtual keywords?
Anyway it would work but I need to know the purpose behind using protected access modifier and virtual. One last thing this code is from MSDN page teaching how to user delegates to kick an event.
using System;
namespace DelegateForEvents
{
using System.Collections;
// A delegate type of hooking up change notificatins.
public delegate void ChangedEventHandler(object sender, EventArgs e);
// A class that works just like ArrayList, but sends notifications whevern the list changes.
public class ListWithChangedEvent : ArrayList
{
// An event that clients can use to be notified whenever the elements of the list change
public event ChangedEventHandler Changed;
// Invoke the Changed event; called whenever list changes
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
Changed(this, e);
}
// Override some of the methods that can change the list;
// Invoke event after each
public override int Add(object value)
{
int i = base.Add(value);
OnChanged(EventArgs.Empty);
return i;
}
public override void Clear()
{
base.Clear();
OnChanged(EventArgs.Empty);
}
public override object this[int index]
{
//get
//{
// return base[index];
//}
set
{
base[index] = value;
OnChanged(EventArgs.Empty);
}
}
}
}
namespace TestEvents
{
using DelegateForEvents;
class EventListener
{
private ListWithChangedEvent List;
public EventListener(ListWithChangedEvent list)
{
List = list;
// Add "ListChanged" to the Changed event on "List"
List.Changed += new ChangedEventHandler(ListChanged);
}
// This will be called whenever the list changes.
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires");
}
public void Detach()
{
// Death the event and delete the list
List.Changed -= new ChangedEventHandler(ListChanged);
List = null;
}
}
class Test
{
// Test the ListWithChangedEvent class
static void Main()
{
// Create a new list
ListWithChangedEvent list = new ListWithChangedEvent();
// Create a class that listens to list's change event
EventListener listener = new EventListener(list);
// Add and remove items from the list.
list.Add("item 1");
list.Clear();
listener.Detach();
Console.ReadLine();
}
}
}
Virtual: this method is intended to be overridden. When calling this method, generate ‘callvirt’ rather than ‘call’ in the IL.
Protected: this method is visible to classes which inherit from this one, but is not publicly callable.