troubleshooting Question

Change source code with Roslyn

Avatar of David DB
David DB asked on
C#
1 Comment1 Solution68 ViewsLast Modified:
Hi

I want to change source code using Roslyn.

I'm using this code now for testing, and will overwrite every property. But dont worry about that:

public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node)
         {
            // remake property with the values from incoming node
            var changedProp =
                 SyntaxFactory.PropertyDeclaration(
                    node.Type,
                    node.Identifier.ValueText + " "
                 )
                 .AddAccessorListAccessors(
                  SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                  SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                  );

            foreach (var modifier in node.Modifiers)
            {
               changedProp = changedProp.AddModifiers(modifier);
            }

            return changedProp;
         }

What I want to do is change code like this:

      internal string Heading
      {
         get
         {
            string HeadingRet = myActivity.Heading;
            return HeadingRet;
         }

         set
         {
            myActivity.Heading = value.substring(0,20);
         }
      }

to

      internal string Heading { get => myActivity.Heading; set => myActivity.Heading = value.substring(0,20); }

My code will just change to:

internal string Heading {get; set;}

What I dont understand is how to make: get => variable; set => variable = value; with Roslyn.

BTW: I will not do this at runtime, but change the source code files for improved code. I'm not looking for personal views on this kind of coding, unless it's fundamentally wrong. And not looking for utilities since they are not flexible enough to do exactly what I want. I want to code the transformation.
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 1 Comment.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros