Home > Mobile >  Not able to access event defined in a class
Not able to access event defined in a class

Time:12-08

I am trying to subscribe a event but it is showing error on the mentioned line. Can anyone tell me what the problem in my code is?

I am new to programming, so kindly please provide a detailed answer. Thanks in advance

namespace Events
{
    delegate void MyEventHandler();

    internal class ArrayListExamplePublisher : ArrayList
    {
        public event MyEventHandler objMyEventHandler;

        void OnAdded()
        {
            if (objMyEventHandler != null)
            {
                objMyEventHandler();
            }
        }

        public override int Add(object? value)
        {
            OnAdded();
            return base.Add(value);
        }
    }

    public class ArrayListExample
    {
        static void Main()
        {
            ArrayList arrayList = new ArrayList();

            // Here I get an error
            arrayList.objMyEventHandler  = () => Console.WriteLine("Object Added"); 
            
            arrayList.Add(1);
            arrayList.Add("4");
        }
    }
}

CodePudding user response:

You are adding the event to ArrayListExamplePublisher, not ArrayList, so when you try to assign that event on an ArrayList, it fails.

You can't add an event to a class externally in C# - you'd have to modify the definition of ArrayList, which you can't do.

You could do:

ArrayListExamplePublisher arrayList = new ArrayListExamplePublisher();

and set the event on that, but it's not clear if that's what you want.

Side note: The framework already has ObservableCollection<T> that has events for when the collection is modified (and is strongly-typed, unlike ArrayList.

CodePudding user response:

Your lambda expression has to match the delegate type for the event.

Most events take two arguments, so this should probably work:

arrayList.objMyEventHandler  = ( s, e ) => Console.WriteLine("Object Added"); 

CodePudding user response:

So i have figured it out As i am inheriting the class ArrayList so I should use object of child class but i was using the object of parent class. This works perfectly

ArrayListExamplePublisher objArrayListExamplePublisher = new ArrayListExamplePublisher();
            objArrayListExamplePublisher.Added  = () => Console.WriteLine("Object Added");
            objArrayListExamplePublisher.Add(1);
            objArrayListExamplePublisher.Add("4");

  • Related