-2

Update : reason for needing this is I need to create complex objects, deeply nested like document object models. I can not tell if all the properties have been initialised, really looking to see if I missed a property, specially when deeply nested.

In Other words , I need to see if the complete Object tree has been in initialised or I missed a property somewhere.

Can we use Roslyn to generate the object InitializerExpressionSyntax only from code? Not trying to decompile the object as in this post : Can Roslyn generate source code from an object instance?

Would it work with complex/nested objects?

Community
  • 1
  • 1
jimjim
  • 2,414
  • 2
  • 26
  • 46
  • 2
    What do you mean by doing *anything* with Roslyn from an "instance" of an object? Roslyn is a compile-time apparatus -- an "instance" of something is the opposite. – Kirk Woll Jun 24 '16 at 02:40
  • @KirkWoll : So lets say in one place an object instance is created with one set of values, somewhere else another instance is created with another set of values, both in code. Just want to collect all possible instance creation values throughout the code, not at the run time. – jimjim Jun 24 '16 at 02:44
  • 1
    Ah, OK, then yeah, Roslyn is totally suitable for this. (and you should really edit your question to make clear that you're talking about `ObjectCreationExpressionSyntax` / `InitializerExpressionSyntax` and not an actual runtime instance) That being said, the answer to your question is "yes", but now it's way too broad. You need to figure out what incremental problem you're actually stuck at. i.e. if the solution is A→B→C→D: you've asked us how to go from A to D. You need to find the small unit of work that is A→B where you're actually stuck. – Kirk Woll Jun 24 '16 at 02:49

1 Answers1

0

Write a program or use T4 template to generate codes from codes.

var code = @"public partial class Abc { public string AAA { get; set; } }";
var syntaxTree = CSharpSyntaxTree.ParseText(code);
var syntax = (CompilationUnitSyntax)syntaxTree.GetRoot();

var @class = syntax.ChildNodes().OfType<ClassDeclarationSyntax>().First();
var properties = @class.ChildNodes().OfType<PropertyDeclarationSyntax>();
foreach (var property in properties)
{
    ...
}
Tommy
  • 3,044
  • 1
  • 14
  • 13