roslyn: IDE0018 suggested incorrectly in lambda in local function

Version Used: Visual Studio 2017 RTM (Visual Studio/15-RTW+26228.4)

Steps to Reproduce:

using System;
using System.Collections.Generic;

class Demo
{
    static void Main()
    {
        F();
        void F()
        {
            Action f = () =>
            {
                Dictionary<int, int> dict = null;
                int x = 0;  // "IDE0018 Variable declaration can be inlined" suggested here
                dict?.TryGetValue(0, out x);
                Console.WriteLine(x);
            };
        }
    }
}

Expected Behavior: IDE0018 is not suggested.

Actual Behavior: IDE0018 is suggested. If I “fix” that, the code will be:

using System;
using System.Collections.Generic;

class Demo
{
    static void Main()
    {
        F();
        void F()
        {
            Action f = () =>
            {
                Dictionary<int, int> dict = null;
                dict?.TryGetValue(0, out int x);
                Console.WriteLine(x);
            };
        }
    }
}

This code contains error:

CS0165 Use of unassigned local variable ‘x’

note: if I put “TryGetValue” block outside of lambda, or put lambda outside of local function, then IDE0018 is not suggested.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 32 (30 by maintainers)

Most upvoted comments

@agocke I’m impressed how you’re trying to justify the broken design/implementation 😃 Absence of definite assignment errors sometimes looks like a compiler bug for users, especially when there is no capturing into closure happens.