Reputation: 30995
Is there a way to use CodeDom to generate an overloaded operator in Vb.net? I want to generate this:
Public Shared Operator =(ByVal x As MyType, ByVal y As MyType) As Boolean
Return x Is y
End Operator
The closest hack I can think of to do this the following:
Dim eq As New CodeMemberMethod()
eq.Name = "Operator ="
eq.Parameters.Add(New CodeParameterDeclarationExpression(New CodeTypeReference("MyType"), "x"))
eq.Parameters.Add(New CodeParameterDeclarationExpression(New CodeTypeReference("MyType"), "y"))
eq.Attributes = MemberAttributes.Public Or MemberAttributes.Static
eq.ReturnType = New CodeTypeReference(GetType(Boolean))
eq.Statements.Add(New CodeMethodReturnStatement(New CodeBinaryOperatorExpression(New CodeVariableReferenceExpression("x"), CodeBinaryOperatorType.IdentityEquality, New CodeVariableReferenceExpression("y"))))
type.Members.Add(eq)
Which generates this, close but obviously wrong:
Public Shared Function Operator =(ByVal x As MyType, ByVal y As MyType) As Boolean
Return (x Is y)
End Function
Upvotes: 1
Views: 521
Reputation: 30995
I hate this solution, but it works.
Dim eq As New CodeSnippetTypeMember("Public Shared Operator =(ByVal x As MyType, ByVal y As MyType) As Boolean" & Environment.NewLine & "Return x Is y" & Environment.NewLine & "End Operator")
type.Members.Add(eq)
I'm sure the correct way has something to do with inheriting from CodeTypeMember to define the member, then inheriting from Microsoft.VisualBasic.VBCodeGenerator to provide the implementation of the member, but I don't have the time to deal with all that. I think it's time to make a switch from CodeDom to T4.
Upvotes: 1