# Delegate
{: .no_toc }

Declares a function-pointer type --- a named signature that variables, parameters, and UDT members can hold a *reference* to a callable matching. A delegate value is bit-compatible with **LongPtr**, but the compiler compares the signature of a procedure assigned to it, and warns when they differ.

> [!NOTE]
> The **Delegate** statement is a twinBASIC extension. In classic VBA, function pointers are untyped **LongPtr** values produced by **AddressOf** and called indirectly through custom mechanisms (`DispCallFunc`, `CallWindowProc` shims, etc.).

Syntax:
- > { **Public** \| **Private** } **Delegate Function** *name* [ *callconv* ] **(** [ *arglist* ] **)** [ **As** *type* ]
- > { **Public** \| **Private** } **Delegate Sub** *name* [ *callconv* ] **(** [ *arglist* ] **)**

**Public**
: *required*, or **Private**: a declaration with neither is a syntax error, TB5182. In an ActiveX project, exports the delegate type to the type library so consumers in other projects see *name*. Not allowed in a class, where a delegate must be **Private** (TB5227, *Delegate declarations in class modules must be Private*).

**Private**
: *required*, or **Public**. Withholds the delegate from the type library; usable only within the project.

*name*
: The identifier naming the delegate type. Must be a valid twinBASIC identifier.

*callconv*
: *optional* The calling convention of the procedures the delegate refers to: **CDecl**, **ThisCall** or **FastCall**. The default is stdcall. A C-runtime callback such as the comparator of `qsort` is **CDecl**. See [Calling Conventions](/Features/Advanced/API-Declarations.md#calling-conventions), which also describes a defect that affects calls through **ThisCall** and **FastCall** delegates on 32-bit builds.

*arglist*
: *optional* Parameter signature, written exactly as for a [**Sub**](/tB/Core/Sub.md) or [**Function**](/tB/Core/Function.md) --- comma-separated `[ ByVal | ByRef ] [ Optional ] *varname* [ As *type* ]` parts.

*type*
: *optional* Return type of a **Function** delegate's signature. Without **As** *type* the return type is **Variant**, and the compiler reports [TB0003](/Features/Compiler-IDE/Compiler-Warnings.md#tb0003-implicit-variant-data-type), as it does for a [**Function**](/tB/Core/Function.md).

After the declaration, *name* may be used wherever a type is allowed: to declare variables and parameters of function-pointer type, as the type of a member of a [**Type**](/tB/Core/Type.md) (UDT), or as a parameter type in a [**Declare**](/tB/Core/Declare.md) statement or an [**Interface**](/tB/Core/Interface.md) member.

A delegate value is normally produced by **AddressOf**, which yields a delegate-typed reference to a regular procedure with a matching signature. A procedure that does not match causes only a warning, TB0026 *Mismatched delegate type*, and the program still builds; its arguments then arrive in a form it does not expect. See [Passing a function as an argument](/Features/Language/Delegates.md#callbacks) for what that looks like and how to make it an error. For backwards compatibility, a delegate variable can also be assigned a plain **LongPtr** address obtained by other means --- the value passes through unchecked. A delegate variable is called like a function: `result = myDelegate(arg1, arg2)`.

### Example

A basic delegate, declared, assigned, and called:

```tb check_build
Private Delegate Function Operation (ByVal A As Long, ByVal B As Long) As Long

Public Function Addition(ByVal A As Long, ByVal B As Long) As Long
    Return A + B
End Function

Private Sub Command1_Click()
    Dim op As Operation = AddressOf Addition
    MsgBox "Answer: " & op(5, 6)
End Sub
```

In a class, a **Private** delegate can stand anywhere among the declarations, and any member can follow it:

```tb check_build
Class Sorter
    Private Delegate Function Comparer (ByVal A As Long, ByVal B As Long) As Long
    Private ReadOnly mCreated As Date = Now()
    Private mCompare As Comparer

    Friend Sub SetComparer(ByVal Compare As Comparer)
        mCompare = Compare
    End Sub
End Class
```

A delegate used as a UDT member, modelling the `lpfnHook` field of the Windows `CHOOSECOLOR` struct. Existing code that assigns a **Long**/**LongPtr** to `lpfnHook` continues to work; new code can assign **AddressOf** *Handler* directly, and the compiler warns if its signature does not match:

```tb inert=external
Public Delegate Function CCHookProc (ByVal hwnd As LongPtr, ByVal uMsg As Long, _
    ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr

Public Type CHOOSECOLOR
    lStructSize As Long
    hwndOwner As LongPtr
    hInstance As LongPtr
    rgbResult As Long
    lpCustColors As LongPtr
    Flags As ChooseColorFlags
    lCustData As LongPtr
    lpfnHook As CCHookProc       ' Typed function pointer instead of LongPtr.
    lpTemplateName As LongPtr
End Type

Dim tCC As CHOOSECOLOR
tCC.lpfnHook = AddressOf ChooseColorHookProc
```

A **CDecl** delegate, used as the comparator parameter of the C-runtime `qsort` API:

```tb check_build
Private Delegate Function LongComparator CDecl ( _
    ByRef a As Long, _
    ByRef b As Long _
) As Long

Private Declare PtrSafe Sub qsort CDecl Lib "msvcrt" ( _
    ByRef pFirst As Any, _
    ByVal lNumber As Long, _
    ByVal lSize As Long, _
    ByVal pfnComparator As LongComparator _
)
```

### See Also

- [**Declare** statement](/tB/Core/Declare.md)
- [**Type** statement](/tB/Core/Type.md)
- [**Interface** statement](/tB/Core/Interface.md)
- [**Alias** statement](/tB/Core/Alias.md)
- [Delegate Types](/Features/Language/Delegates.md)
- [API Declarations](/Features/Advanced/API-Declarations.md)
- [Enhanced Pointer Functionality](/Features/Language/Pointers.md)
