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;
         }

Open in new window


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);
         }
      }

Open in new window


to

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

Open in new window


My code will just change to:

internal string Heading {get; set;}

Open in new window


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.
ASKER CERTIFIED SOLUTION
David DB

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 1 Comment.
Start Free Trial
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