65.9K
CodeProject is changing. Read more.
Home

Use Lambda Expressions as Unmanaged Callbacks

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Nov 4, 2010

CPOL
viewsIcon

17730

An application of lambda expressions to simplify your code.

Unmanaged functions often require callback functions, and we sometimes have to call such functions from C# program. This is a sample which calls EnumWindows without lambda.
class Program
{
    [DllImport("user32", ExactSpelling = true)]
    static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, IntPtr lParam);

    [UnmanagedFunctionPointer(CallingConvention.Winapi)]
    delegate bool WNDENUMPROC(IntPtr hwnd, IntPtr lParam);
    
    static List<IntPtr> windows;
    
    static bool WndEnumCallback(IntPtr hwnd, IntPtr lParam)
    {
        windows.Add(hwnd);
        return true;
    }

    static void Main(string[] args)
    {
        windows = new List<IntPtr>();
        EnumWindows(new WNDENUMPROC(WndEnumCallback), IntPtr.Zero);
        // Some work using window handles.
    }
}
You should promote a code block cannot be reused to a member method, and a mere temporary variable to a field. It makes your code needlessly complex. Since C# 3.0, you can use a lamdba expression to simplify it.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("user32", ExactSpelling = true)]
    static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, IntPtr lParam);

    [UnmanagedFunctionPointer(CallingConvention.Winapi)]
    delegate bool WNDENUMPROC(IntPtr hwnd, IntPtr lParam);

    static void Main(string[] args)
    {
        List<IntPtr> windows = new List<IntPtr>();
        WNDENUMPROC callback = (hwnd, lParam) =>
        {
            windows.Add(hwnd);
            return true;
        };

        EnumWindows(callback, IntPtr.Zero);

        // Some work using window handles.
    }
}
In this code, you can define a temporary variable and a non-reusable code block as local variables.