HotCommands icon indicating copy to clipboard operation
HotCommands copied to clipboard

InvalidOperationException on InitializeFieldFromConstructor

Open verysimplenick opened this issue 7 years ago • 6 comments

Hi. In VS 2017.2 often see exception in InitializeFieldFromConstructor while edit code in .net core projects (1.1).

System.InvalidOperationException : Sequence contains more than one element
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at HotCommands.InitializeFieldFromConstructor.GetConstructors(VariableDeclaratorSyntax fieldVariable)
   at async HotCommands.InitializeFieldFromConstructor.ComputeRefactoringsAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringService.GetRefactoringFromProviderAsync(<Unknown Parameters>)

verysimplenick avatar Jun 25 '17 20:06 verysimplenick

I think I get error while have 2 classes on one file in .net core project. Check this please, I think need something condition in FirstOrDefault to search class with this field in file.

verysimplenick avatar Jun 25 '17 20:06 verysimplenick

Is this different to the issue fixed by pull request #67 ? (I haven't uploaded the new built VSIX since Loren made the fix.)

Or is this a separate issue?

justcla avatar Jun 26 '17 01:06 justcla

I think separate (NullReferenceException in #67 vs InvalidOperationException #69)

verysimplenick avatar Jun 26 '17 05:06 verysimplenick

@justcla This is a different issue from #67.

This problem is (obviously - from the stack trace) the SingleOrDefault() from var classDeclaration = fieldVariable.Ancestors().OfType<ClassDeclarationSyntax>().SingleOrDefault();

meaning the field variable has multiple ancestors. This happens with nested classes.

SingleOrDefault -> FirstOrDefault would indeed prevent the problem, and it seems the order in Ancestors() is innermost->outermost, so this seems to be the correct fix.

I'm quite sure fix can be applied, and issue closed.

tamlin-mike avatar Oct 14 '17 05:10 tamlin-mike

I've uploaded a new VSIX with the fix suggested by Mike. v1.1.7 @tamlin-mike @verysimplenick Can you please confirm if this fixes the issue?

justcla avatar Oct 15 '17 05:10 justcla

As I'm using my home-built binary, I can only confirm that it works (as expected).

Additionally, it was @verysimplenick providing the patch (Jun 25). I just commented (and documented a bit) since I was now bitten by the bug too.

tamlin-mike avatar Oct 15 '17 06:10 tamlin-mike