Search code examples
c#lambdacallbackkeywordunsafe

Apply an `unsafe` keyword to a lambda expression in C#


Why is it impossible to apply an unsafe keyword to a lambda expression in C#?

Here is what I tried:

using System;

public class Program
{
    public static void Main()
    {
        Action<int> a = unsafe i => Console.WriteLine(i);
    }
}

Here is the fiddle: https://dotnetfiddle.net/nBI0dX.

Here is the error I got:

Invalid expression term 'unsafe'

I need this solely for studying purposes. I am learning the .NET and see no reasons to prohibit the unsafe keyword before a lambda expression. So, I am interested why it might have been prohibited.


Solution

  • Consider using local function instead, which has some advantages over lambda expression and supports unsafe keyword:

    using System;
    
    public class Program
    {
        public static void Main()
        {
            unsafe void a(int i) => Console.WriteLine(i);
        }
    }