Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix InvalidCastException when initializing the properties of an undec…
…lared class inside a lambda function (#72480) Fixes #72456. Building the following snippet in a VB project breaks the compilation: ```vb Imports System Imports System.Linq.Expressions Module Program Public Function CreateExpression() As Expression(Of Func(Of Object)) Return Function() (New UndeclaredClass() With {.Name = "testName"}) End Function End Module ``` There is a difference between `VisualBasic` and `CSharp` when getting diagnostics for the snippet above. The latter checks for the initializer type while the former forces a `DirectCast` which throws an `InvalidCastException`. This PR checks the type before forcing the cast similar to the `CSharp` approach. ### Expected result `Error BC30002: Type 'UndeclaredClass' is not defined.` ### Actual result Compilation breaks with the following trace: ``` System.InvalidCastException HResult=0x80004002 Message=Unable to cast object of type 'Microsoft.CodeAnalysis.VisualBasic.BoundLiteral' to type 'Microsoft.CodeAnalysis.VisualBasic.BoundAssignmentOperator'. This exception was originally thrown at this call stack: Microsoft.CodeAnalysis.VisualBasic.dll!Microsoft.CodeAnalysis.VisualBasic.DiagnosticsPass.VisitObjectInitializerExpression(Microsoft.CodeAnalysis.VisualBasic.BoundObjectInitializerExpression node) Line 126 Basic Microsoft.CodeAnalysis.VisualBasic.dll!Microsoft.CodeAnalysis.VisualBasic.BoundObjectInitializerExpression.Accept(Microsoft.CodeAnalysis.VisualBasic.BoundTreeVisitor visitor) Line 3792 Basic Microsoft.CodeAnalysis.VisualBasic.dll!Microsoft.CodeAnalysis.VisualBasic.BoundTreeWalkerWithStackGuard.VisitExpressionWithoutStackGuard(Microsoft.CodeAnalysis.VisualBasic.BoundExpression node) Line 61 Basic Microsoft.CodeAnalysis.VisualBasic.dll!Microsoft.CodeAnalysis.VisualBasic.BoundTreeVisitor.VisitExpressionWithStackGuard(Integer recursionDepth, Microsoft.CodeAnalysis.VisualBasic.BoundExpression node) Line 186 Basic Microsoft.CodeAnalysis.VisualBasic.dll!Microsoft.CodeAnalysis.VisualBasic.BoundTreeWalkerWithStackGuard.Visit(Microsoft.CodeAnalysis.VisualBasic.BoundNode node) Line 50 Basic Microsoft.CodeAnalysis.VisualBasic.dll!Microsoft.CodeAnalysis.VisualBasic.DiagnosticsPass.Visit(Microsoft.CodeAnalysis.VisualBasic.BoundNode node) Line 208 Basic ... ```
- Loading branch information