Link to home
Start Free TrialLog in
Avatar of hemanthsharma
hemanthsharma

asked on

Regarding delegates...

Hello experts !!!

I would like to declare fields , methods and properties
within a delegate.

The delegate should look & act like a class.

How can i achieve this ?
Avatar of _TAD_
_TAD_


The short answer...

use Interfaces, not delegates.

Interfaces and Delegates are essentially the same thing.

[from MSDN]

Delegates vs. Interfaces

Delegates and interfaces are similar in that they enable the separation of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification. When should you use interfaces, and when should you use delegates?

Delegates are useful when:

A single method is being called.
A class may want to have multiple implementations of the method specification.
It is desirable to allow using a static method to implement the specification.
An event-like design pattern is desired (for more information, see the Events Tutorial).
The caller has no need to know or obtain the object that the method is defined on.
The provider of the implementation wants to "hand out" the implementation of the specification to only a few select components.
Easy composition is desired.


Interfaces are useful when:

The specification defines a set of related methods that will be called.
A class typically implements the specification only once.
The caller of the interface wants to cast to or from the interface type to obtain other interfaces or classes.


If you are still hell-bent on using a delegate, I don't think you can get the exact functionality that you are looking for.

A Delegate is merely a pointer to an already existing class structure (almost always a method or function).


public delegate void myDelegate();


public class myClass
{
    myDelegate del1;
 
    public myClass()
    {
       del1 += method1();
       del1 += method2();

       del1();  // executes method1(), then executes method2()
    }
 
    private void method1() { //stuff }

    private void method2() { //stuff }
   

}


On the other hand an interface acts a lot more like a class.


public interface ITest
{
 
   void method1();

   string function1(string);

}


As for specifying fields.... you cannot do that with either delegates or interfaces...



What exactly are you trying to accomplish?  
Avatar of hemanthsharma

ASKER

A delegate name and the constructor name must be the same.


So, in such a situation, how can we add variables & properties to tat particular delegate class?

I have increased the points ..!>!>! >!>
ASKER CERTIFIED SOLUTION
Avatar of _TAD_
_TAD_

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial