-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Closed
Labels
Description
Version Used: 14.4
Steps to Reproduce:
A sample repo is created to demonstrate the bug:
- Create a C# class library project and declare the following attributes:
using System;
namespace ClassLib
{
public class TestAttribute : Attribute
{
public required string? Name { get; init; }
}
}
- Create a VB.Net test project with xUnit test:
Imports System.Reflection
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Xunit
Namespace ClassLib
Public Class TestAttributeTest
Private Class TestClass
<Test(Name:="MyName")>
Public Sub TestMethod()
End Sub
End Class
<Fact>
Sub TestAttributeViaReflection()
Dim type = GetType(TestClass)
Dim attribute = type.GetMethod(NameOf(TestClass.TestMethod)).GetCustomAttribute(Of TestAttribute)()
Assert.Equal("MyName", attribute.Name)
End Sub
<Fact>
Sub TestAttributeViaRoslyn()
Dim sourceCode As String = "
Public Class TestClass
<Test(Name:=""MyName"")>
Public Sub TestMethod()
End Sub
End Class
"
Dim syntaxTree As SyntaxTree = VisualBasicSyntaxTree.ParseText(sourceCode)
Dim classlib As MetadataReference = MetadataReference.CreateFromFile(GetType(TestAttribute).Assembly.Location)
Dim compilation As Compilation = VisualBasicCompilation.Create("MyCompilation", New SyntaxTree() {syntaxTree}, New MetadataReference() {classlib})
Dim type As INamedTypeSymbol = compilation.GetTypeByMetadataName("TestClass")
Assert.NotNull(type)
Dim method As IMethodSymbol = type.GetMembers().OfType(Of IMethodSymbol)().Where(Function(x) x.Name = "TestMethod").Single()
Dim attributeData As AttributeData = method.GetAttributes().Single()
Dim testAttributeType As INamedTypeSymbol = compilation.GetTypeByMetadataName("ClassLib.TestAttribute")
Assert.NotNull(testAttributeType)
Assert.True(SymbolEqualityComparer.Default.Equals(testAttributeType, attributeData.AttributeClass))
End Sub
End Class
End Namespace
Expected Behavior:
- The test project should compile correctly without any error in IDE;
- The unit test should pass.
Actual Behavior:
- The
TestAttributeused in the test project is shown with a strike line in Visual Studio:
It appears VB.Net compiler does not handle attribute with required init property correctly. Change class TestAttribute to the following will fix it:
public class TestAttribute : Attribute
{
public string? Name { get; set; }
}
- The test
TestAttributeViaRoslynfailed, with or without required init property. It appears the returnedAttributeData.AttributeClassis an error type (ISymbol.Kind == ErrorType).