Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
public delegate void myDelecate();
class A
    {
        public event myDelecate myEvent;
    public void everaise()
        {
        if(myEvent!=null)
                myEvent();
        }
     }
class Program
    {
        static void Main(string[] args)
        {
        A obj = new A();
            obj.myEvent += new myDelecate(DEF);
            obj.everaise();
    Console.ReadLine();
        }

        public static void DEF()
        {
            Console.WriteLine("DEF method called");
        }
}


how to make these codes into a single line of code,
obj.myEvent += new myDelecate(DEF);
obj.everaise();
Posted
Updated 8-Oct-15 23:47pm
v5
Comments
Tomas Takac 9-Oct-15 3:37am    
Not clear. Are you asking about what happens if you do this at the same time from two threads?
MVK_VIJI 9-Oct-15 4:24am    
if u understand now please answer me, use only events and delegates
Tomas Takac 9-Oct-15 4:46am    
No, I don't understand. And your other comment didn't help either.
Tomas Takac 9-Oct-15 5:13am    
I read you updated question and I'm still not sure what are you asking. But it sounds like you found your solution.
MVK_VIJI 9-Oct-15 5:21am    
ok just run the above program you got a output.
are you understand the above program , how it should run and work

1 solution

You can have custom add/remove handlers for an event:
C#
class A
{
    private myDelecate del;
    public event myDelecate myEvent
    {
        add
        {
            del += value; // add handler
            value(); // call the method being added
            //del(); // call all the methods added so far
        }
        remove
        {
            del -= value;
        }
    }
}

And you don't need to call the public method to raise the event:
C#
void Main()
{
    A obj = new A();
    obj.myEvent += new myDelecate(DEF);
    //obj.everaise();
}

Please note that this will only invoke the delegate being added. Your original solution invoked all the delegates that were added to the event.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900