Reputation: 17627
If I want to add a new property to a type do I need to rebuild the whole type or is there a way to add property to existing type? Since one can only replace the nodes, do I have to replace the whole class declaration node? If so how would one do it?
Only way I have found to do this is dirty, and basically boils down to getting the source code of the type, finding the first open bracket, and inserting new source code for property, then parsing the resulting text and then replacing old class declaration node with a new one.
Something like this:
var toTypeSymbol =(TypeSymbol)compilation.GetTypeByMetadataName(propertyTypeInfo.ToString());
var toTypeDeclarationSyntax = (ClassDeclarationSyntax) toTypeSymbol.DeclaringSyntaxNodes.First();
var origToTypeCode = toTypeSymbol.DeclaringSyntaxNodes.First().ToFullString();
var idx = origToTypeCode.IndexOf("{")+1;
var newPropertyCode = String.Format(@" protected internal virtual {0} {0} {{get;set;}}",classSymbol.Name);
var newTypeCode = origToTypeCode.Insert(idx, newPropertyCode);
var newType = Syntax.ParseCompilationUnit(newTypeCode).NormalizeWhitespace();
var classDeclarationSyntax = newType.ChildNodes().OfType<ClassDeclarationSyntax>().First();
var temp = toTypeDeclarationSyntax.Parent.ReplaceNode(toTypeDeclarationSyntax,classDeclarationSyntax).NormalizeWhitespace();
Console.WriteLine(temp.ToFullString());
Upvotes: 1
Views: 117
Reputation: 11605
You could take a look at the ImplementINotifyPropertyChanged
sample that is included in the CTP. One of the things it does is add an event, and a method. The same strategy applies to properties.
Upvotes: 3