Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7435879
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T10:08:56+00:00 2026-05-29T10:08:56+00:00

Consider the following class in a file MyClass.cs using System; public class MyClass :

  • 0

Consider the following class in a file “MyClass.cs”

using System;

public class MyClass : Entity<long>
{
    public long Id
    {
        get;
        set;
    }

    [Required]
    public string Name
    {
        get;
        set;
    }

    public string Slug
    {
        get;
        set;
    }

    public DateTime CreatedOn
    {
        get;
        private set;
    }

    public DateTime UpdatedOn
    {
        get;
        private set;
    }

    /* ... */
}

Currently I manually create data contract classes looking as follows:

[DataContract(Namespace = "http://example.com/", Name = "MyClass")]
public sealed class MyClass
{
    [DataMember(EmitDefaultValue = false, Name = "Id")]
    public long Id
    {
        get;
        set;
    }

    [DataMember(EmitDefaultValue = false, Name = "Name", IsRequired = true)]
    public string Name
    {
        get;
        set;
    }

    [DataMember(EmitDefaultValue = false, Name = "Slug")]
    public string Slug
    {
        get;
        set;
    }

    [DataMember(EmitDefaultValue = false, Name = "CreatedOn")]
    public DateTime CreatedOn
    {
        get;
        set;
    }

    [DataMember(EmitDefaultValue = false, Name = "UpdatedOn")]
    public DateTime UpdatedOn
    {
        get;
        set;
    }
}

I’d like to use Roslyn to rewrite “MyClass.cs” so its looks like the class I create by hand. Currently I have the following:

using System;
using System.IO;
using Roslyn.Compilers.CSharp;

internal class Program
{
    private static void Main()
    {
        var reader = new StreamReader(@"..\..\MyClass.cs");
        var source = reader.ReadToEnd();
        var tree = SyntaxTree.ParseCompilationUnit(source);
        var rewriter = new MyRewriter();
        var newRoot = rewriter.Visit(tree.Root);
        Console.WriteLine(newRoot.Format());
    }
}

public class MyRewriter : SyntaxRewriter
{
    protected override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        var declaration = (TypeDeclarationSyntax) base.VisitClassDeclaration(node);

        return ((ClassDeclarationSyntax) declaration).Update(
            declaration.Attributes,
            Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword), Syntax.Token(SyntaxKind.SealedKeyword)),
            declaration.Keyword,
            declaration.Identifier,
            declaration.TypeParameterListOpt,
            null,
            declaration.ConstraintClauses,
            declaration.OpenBraceToken,
            declaration.Members,
            declaration.CloseBraceToken,
            declaration.SemicolonTokenOpt);
    }

    protected override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node)
    {
        var typeSyntax = node.Type;

        if (node.Identifier.ValueText == "Id")
        {
            typeSyntax = Syntax.IdentifierName("string");
        }

        var newProperty = Syntax.PropertyDeclaration(
            modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword)),
            type: typeSyntax,
            identifier: node.Identifier,
            accessorList: Syntax.AccessorList(
                accessors: Syntax.List(
                    Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, 
                    semicolonTokenOpt: Syntax.Token(SyntaxKind.SemicolonToken)),
                    Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration,
                    semicolonTokenOpt: Syntax.Token(SyntaxKind.SemicolonToken))
                    )
                )
            );

        return newProperty;
    }
}

I have been trying to find a way to add the DataMember and DataContract custom attributes to MyClass but have been unsuccessful. How does one add the custom attributes?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T10:08:56+00:00Added an answer on May 29, 2026 at 10:08 am

    One of the parameters of the Syntax.PropertyDeclaration method is a list of attributes that apply to the attribute. Like all Syntax elements, it is constructed using a factory method on the static SyntaxFactory class.

    The Roslyn Quoter can be handy for figuring out how to generate syntax using Roslyn.

    In your particular example, the VisitPropertyDeclaration method of your rewriter should look something like:

    using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
    ...
    
        protected override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node)
    {
        var typeSyntax = node.Type;
    
        if (node.Identifier.ValueText == "Id")
        {
            typeSyntax = SyntaxFactory.IdentifierName("string");
        }
    
        var newProperty = PropertyDeclaration(
                    PredefinedType(
                        Token(SyntaxKind.LongKeyword)),
                    Identifier("Id"))
                .WithModifiers(
                    TokenList(
                        Token(SyntaxKind.PublicKeyword)))
                .WithAccessorList(
                    AccessorList(
                        List(new AccessorDeclarationSyntax[]{
                            AccessorDeclaration(
                                SyntaxKind.GetAccessorDeclaration)
                            .WithSemicolonToken(
                                Token(SyntaxKind.SemicolonToken)),
                            AccessorDeclaration(
                                SyntaxKind.SetAccessorDeclaration)
                            .WithSemicolonToken(
                                Token(SyntaxKind.SemicolonToken))})))
                .NormalizeWhitespace();
    
        return newProperty;
    }       
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider the following class hierarchy: public class Foo { public string Name { get;
Consider the following class public class Class1 { public int A { get; set;
Consider the following Hibernate mapping file: <hibernate-mapping ...> <class name=ContentPackage table=contentPackages> <id name=Id column=id
consider the following class: class Order { int OrderId {get; set;} int CustomerId {get;
Consider following example : public class SomeBusinessLayerService : DataService<MyEntityContainer> { [WebInvoke] void DoSomething(string someParam)
Consider the following class public class PlanetKrypton { public static void CallSuperManforHelp(string helpMessage, params
Consider following class class test { public: test(int x){ cout<< test \n; } };
Consider the following class: class Something : ISomething { public void DoesSomething(int x) {
Consider the following code: class Program { static void Main(string[] args) { Department deathStar
Consider the following code: class A { public: virtual void f() throw ( int

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.