Avatar of David DB
David DB

asked on 

Change source code with Roslyn

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.
C#

Avatar of undefined
Last Comment
David DB

8/22/2022 - Mon