'How do I address this MSB6006 csc.exe error (-2146232797) with VS2019?

I just updated my VS2019 community edition to Version 16.7.2. My project started failing to build (maybe link step?) with this error (it was previously building just fine, I think on v16.6.something):

> Severity  Code    Description Project File    Line    Suppression State
> Error MSB6006 "csc.exe" exited with code
> -2146232797.  MyProject.Server    C:\Program Files\dotnet\sdk\3.1.401\Sdks\Microsoft.NET.Sdk.Razor\build\netstandard2.0\Microsoft.NET.Sdk.Razor.Component.targets 179

I really don't know how to figure out what is going on. What can I look at next? Should I ask this question somewhere else?

I found this in my Windows event logs. It seems to be a call stack:

> Application: csc.exe Framework Version: v4.0.30319 Description: The
> application requested process termination through
> System.Environment.FailFast(string message). Message:
> System.NullReferenceException: Object reference not set to an instance
> of an object. at
> Microsoft.CodeAnalysis.CodeGen.ILBuilder.BasicBlock.ShortenBranches(Int32&
> delta) at
> Microsoft.CodeAnalysis.CodeGen.ILBuilder.ComputeOffsetsAndAdjustBranches()
> at Microsoft.CodeAnalysis.CodeGen.ILBuilder.RealizeBlocks() at
> Microsoft.CodeAnalysis.CodeGen.ILBuilder.Realize() at
> Microsoft.CodeAnalysis.CSharp.CodeGen.CodeGenerator.GenerateImpl() at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler.GenerateMethodBody(PEModuleBuilder
> moduleBuilder, MethodSymbol method, Int32 methodOrdinal,
> BoundStatement block, ImmutableArray`1 lambdaDebugInfo,
> ImmutableArray`1 closureDebugInfo, StateMachineTypeSymbol
> stateMachineTypeOpt, VariableSlotAllocator variableSlotAllocatorOpt,
> DiagnosticBag diagnostics, DebugDocumentProvider
> debugDocumentProvider, ImportChain importChainOpt, Boolean
> emittingPdb, Boolean emitTestCoverageData, ImmutableArray`1
> dynamicAnalysisSpans, AsyncForwardEntryPoint entryPointOpt) at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileMethod(MethodSymbol
> methodSymbol, Int32 methodOrdinal, ProcessedFieldInitializers&
> processedInitializers, SynthesizedSubmissionFields
> previousSubmissionFields, TypeCompilationState compilationState) at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileNamedType(NamedTypeSymbol
> containingType) at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler.<>c__DisplayClass22_0.<CompileNamedTypeAsync>b__0()
> Stack: at System.Environment.FailFast(System.String, System.Exception)
> at Microsoft.CodeAnalysis.FailFast.OnFatalException(System.Exception)
> at
> Microsoft.CodeAnalysis.FatalError.ReportUnlessCanceled(System.Exception)
> at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler+<>c__DisplayClass22_0.<CompileNamedTypeAsync>b__0()
> at
> Microsoft.CodeAnalysis.CodeGen.ILBuilder+BasicBlock.ShortenBranches(Int32
> ByRef) at
> Microsoft.CodeAnalysis.CodeGen.ILBuilder.ComputeOffsetsAndAdjustBranches()
> at Microsoft.CodeAnalysis.CodeGen.ILBuilder.RealizeBlocks() at
> Microsoft.CodeAnalysis.CodeGen.ILBuilder.Realize() at
> Microsoft.CodeAnalysis.CSharp.CodeGen.CodeGenerator.GenerateImpl() at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder,
> Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol, Int32,
> Microsoft.CodeAnalysis.CSharp.BoundStatement,
> System.Collections.Immutable.ImmutableArray`1<Microsoft.CodeAnalysis.CodeGen.LambdaDebugInfo>,
> System.Collections.Immutable.ImmutableArray`1<Microsoft.CodeAnalysis.CodeGen.ClosureDebugInfo>,
> Microsoft.CodeAnalysis.CSharp.StateMachineTypeSymbol,
> Microsoft.CodeAnalysis.CodeGen.VariableSlotAllocator,
> Microsoft.CodeAnalysis.DiagnosticBag,
> Microsoft.CodeAnalysis.CodeGen.DebugDocumentProvider,
> Microsoft.CodeAnalysis.CSharp.ImportChain, Boolean, Boolean,
> System.Collections.Immutable.ImmutableArray`1<Microsoft.CodeAnalysis.CodeGen.SourceSpan>,
> AsyncForwardEntryPoint) at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileMethod(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol,
> Int32, ProcessedFieldInitializers ByRef,
> Microsoft.CodeAnalysis.CSharp.SynthesizedSubmissionFields,
> Microsoft.CodeAnalysis.CSharp.TypeCompilationState) at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileNamedType(Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)
> at
> Microsoft.CodeAnalysis.CSharp.MethodCompiler+<>c__DisplayClass22_0.<CompileNamedTypeAsync>b__0()
> at
> Roslyn.Utilities.UICultureUtilities+<>c__DisplayClass5_0.<WithCurrentUICulture>b__0()
> at System.Threading.Tasks.Task.Execute() at
> System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
> System.Threading.ContextCallback, System.Object, Boolean) at
> System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
> System.Threading.ContextCallback, System.Object, Boolean) at
> System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task
> ByRef) at System.Threading.Tasks.Task.ExecuteEntry(Boolean) at
> System.Threading.ThreadPoolWorkQueue.Dispatch()


Solution 1:[1]

My question was about how to investigate. Here's what I did, hoping it helps others.

  1. Start deleting code from my project, one file at a time until I found the offending file.
  2. Put that file back, start deleting function bodies one at a time until I found the one that was a problem.
  3. Comment out parts of the offending function until I found the bit of code that was a problem.
  4. Create a new console application and paste in the offending code.
  5. Report the problem to Microsoft as described here: https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio?view=vs-2019

For what it's worth, here's the issue I reported: https://developercommunity.visualstudio.com/content/problem/1162150/vs2019-cscexe-bug-with-switch-statement.html

(If you got to this Stack Overflow searching for similar issues, there is a chance you hit the same thing I did, but it seems like this error is generally "you wrote code that we couldn't even compile."... hopefully the steps above help you out.)

Solution 2:[2]

The stack trace says System.NullReferenceException: Object reference not set to an instance of an object.

Did you try to run the app locally in VS and debug it?

Solution 3:[3]

I ran into this problem on a build server after Windows version was updated.

c:\program files (x86)\microsoft visual studio\2019\buildtools\msbuild\current\bin\Roslyn\Microsoft.CSharp.Core.targets(70,5): error MSB6006: "csc.exe" exited with code -2146232576.

Ultimately for me, I took the output of line 70 of Microsoft.CSharp.Core.targets, which basically is the command line for csc.exe along with all of its command line parameters and ran it from the command line.

That's when a dialog box popped up and said that I needed .net Framework 4.7.2!!! example 4.7.2 error dialog

Here's how you can debug obscure csc.exe errors:

  1. run msbuild with /verbosity:diag and send output to file

    msbuild my.sln /verbosity:diag > output.txt

  2. find the 1st error in the console output by searching for the string "FAILED." to zero in on the failed target and identify the target name and task id (TaskId is 431 in the example)

Task Id example

  1. scan upwards in the diagnostic trace looking for output from the target's task id you identified above, all of the output of that target is marked with that target's task id, see anything unusual?

  2. if your build works on other machines run a diagnostic trace on both (see step 1) and compare the two with a tool like WinMerge

  3. open the target file and look at the line that error'd out, the line number is show in parenthesis next to the error, in the example below it is line 70,

    Microsoft.CSharp.Core.targets(70,5): error MSB6006: "csc.exe"

  4. then open the target and inspect it, what was it trying to do? does it give you any clues as to what might have gone wrong? can you replicate what it is trying to do?

Solution 4:[4]

D.A.s experience is exactly the same as mine. Just slightly different issue. I would comment but can't. In my cause it was also an issue with switches but not quite the same:

public static void Test()
{
    StringSplitOptions temp = StringSplitOptions.None;
    switch (temp)
    {
        case StringSplitOptions.None:
            break;

        case StringSplitOptions.RemoveEmptyEntries:
            {
                using var streamReader = new StreamReader("file1.txt"); // NOT ALLOWED WITH GOTO
                goto case StringSplitOptions.None;
            }

        default:
            break;
    }
}

Bug report FWIW, but the real lesson is just to make sure you check your code before going to drastic measures like hot-swapping nuget packages and re-installing versions of .NET (like I did!).

Solution 5:[5]

After trying many of the solutions found, this one worked for me:

  • Reboot
  • download and install .NET 4.8
  • download and install .NET 6.0

Official page: https://dotnet.microsoft.com/en-us/download

I installed both the runtime and the SDK. After that, repair the Visual Studio from the control panel.

Reboot and (in my case) it was solved. hope it helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 D. A.
Solution 2 Ventsislav Petrov
Solution 3
Solution 4 David
Solution 5