Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate declaration

Tags:

c#

Hi I have summarized my problem in following code snippet. In the first code i have declared a delegate and event in the same class while in Code 2 i have declared delegate and event in separate class.

Code 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        delegate void Greeting(string s);
        event Greeting myEvent;
        void OnFire(string s)
        {
            if (myEvent != null)
                myEvent(s);

        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.myEvent += new Greeting(obj_myEvent);
            obj.OnFire("World");
        }

        static void obj_myEvent(string s)
        {
            Console.WriteLine("Hello " + s + "!");
        }
    }
}

code 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DelegateDemo obj = new DelegateDemo();
            obj.myEvent+=new DelegateDemo.Greeting(obj_myEvent);
            obj.OnFire("World");
        }

        static void obj_myEvent(string s)
        {
            Console.WriteLine("Hello "+s +"!");
        }
    }
}

DelegateDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class DelegateDemo
    {
       public delegate void Greeting(string s);
       public event Greeting myEvent;
       public void OnFire(string s)
        {
            if (myEvent != null)
                myEvent(s);

        }
    }
}

Now i have one question.Is there any diffrence (like thread safe ,performance) between these two code snippets?

like image 873
santosh singh Avatar asked Apr 28 '26 08:04

santosh singh


2 Answers

The only difference seems to be the use of a separate class. So no: as long as the methods and types are accessible there is very little functional difference.

As a side note, you may want to consider Action<string> for a delegate that takes a string and returns void, but also note that events should generally follow the (object sender, SomeEventArgsClass e) pattern (where SomeEventArgsClass:EventArgs, perhaps also using EventHandler<T>)

like image 108
Marc Gravell Avatar answered Apr 29 '26 20:04

Marc Gravell


Actually there is no difference, but you should define delegates outside of classes since a delegate IS a class (deriving from from Delegate).

like image 28
Jaster Avatar answered Apr 29 '26 20:04

Jaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!