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);
}
}
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);
}
}
In this code, you can define a temporary variable and a non-reusable code block as local variables.