Delegates

From The Oxygene Language Wiki

Jump to:navigation, search

This is a Language topic
Feel free to add your notes to this topic below.



A delegate in Delphi Prism is a function pointer type. Delegates are a safe way of dynamically invoking methods with a specific signature on unrelated classes.

Delegates in .NET are often used in combination with events, where the event has a simple way to add and remove a handler. A delegate contains two pointers, a "self" pointer, pointing to the instance of the class to be invoked, and a method pointer.


Defining delegates

Defining a delegate can be done with the function, procedure, method or delegate keyword. Although it's not a requirement, delegates often use the same signature, where the first parameter is the sender, typed System.Object, and the second one is an EventArgs or a descendant of that class.

type
  ClickEventDelegate = delegate (sender: Object; args: EventArgs);


Invoking delegates

To invoke a delegate, one of its members, like BeginInvoke, Invoke or EndInvoke can be called. It's also possible to invoke a delegate by using it as a statement:

type
  MyDelegate = delegate;

..
var
  meth: MyDelegate;
begin
  meth;
  meth();
end;

Both will invoke the delegate.


Further Info

You can assign a method to a delegate:

type
  MyDelegate = delegate;

  MyClass = public partial class
    public
      method ClassMethod;
      DelegateVar: MyDelegate;
  end;
..
begin
  DelegateVar := @ClassMethod;
end;

One important use of a delegate variable is to register a callback function into unmanaged code. If you need to pass a function pointer to unmanaged code, you could obtain a function pointer via the delegate variable rather than the method itself. This will ensure that the function pointer remains in scope for the lifetime of your object:

var i: IntPtr;
begin
  i := Marshal.GetFunctionPointerForDelegate(DelegateVar);
end;


See Also


Oxygene-48.png

Area: Oxygene Language
Compiler version: Oxygene 5

Language GlossaryKeywordsTypesFAQHow To

Navigation
Areas
More
Toolbox