As the error message says in the second case, the linepublic delegate void OnDataAvailable(char[] data);
declares a type, not a member field.
You can think of it as a class that represents a collection of methods with a specific signature - but in this case, the C# language provides a special mechanism and a special keyword ("delegate") used for such declarations.
As with nested classes, you can nest a delegate within a class, but you don't have to - you can declare it within the namespace.
For example:
Code:
namespace Test
{
// declares a TYPE VoidMethod...
public delegate void VoidMethod();
public class MyClass
{
// declares a nested TYPE MyClass.WorkerMethod...
public delegate void WorkerMethod(object obj);
}
}
But these are just type declarations, they don't really do anything.
Once you've defined the delegate types, you can have member fields of those types.
Code:
namespace Test
{
// declares a TYPE VoidMethod...
public delegate void VoidMethod();
public class MyClass
{
// declares a nested TYPE MyClass.WorkerMethod...
public delegate void WorkerMethod(object obj);
// fields
private VoidMethod voidMethodDelegate = null; // this one will, for example, be used internally, so I won't expose it
private WorkerMethod workerDelegate = null;
// A property to expose the workerDelegate field.
public WorkerMethod Worker
{
get { return workerDelegate; }
set { workerDelegate = value; }
}
}
}
To access this delegate from another class you would write:
Code:
MyClass temp = new MyClass();
temp.Worker += new SomeMethodName;
//...
// later on, invoke the delegate...
temp.Worker(someParameter);
Note that the "+=" is generally used to add methods, and "-=" is used to remove them. The invocation runs all the associated methods. You can initialize/modify the delegates in the constructor, or in some other convenient place.
Bookmarks