I'm trying to write a function that takes in an existing Type, and converts the Type to a PropertyDeclaration. I almost have it working, but if the Type I pass in is Nullable, I get this error when I eventually try to compile my class with it: System.BadImageFormatException: is not a valid Win32 application. (Exception from HRESULT: 0x800700C1).
Here's my code:
var classDeclaration = SyntaxFactory.ClassDeclaration("class name");
classDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
classDeclaration.AddMembers(ConvertToProperty(myType, myTypeName));
private static PropertyDeclarationSyntax ConvertToProperty(Type propertyType, string propertyName)
{
var typeSyntax = SyntaxFactory.ParseTypeName(propertyType.ToString());
var propertyDeclaration = SyntaxFactory.PropertyDeclaration(typeSyntax, propertyName)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
.AddAccessorListAccessors(
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
return propertyDeclaration;
}
The class will compile just fine if the Type I pass in is not nullable. I'm not very familiar with Roslyn and I haven't found any examples online of someone doing what i'm trying to do. Is anyone more familiar and has an idea?