Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate empty get & set statements using CODEDOM in c#

Tags:

c#-4.0

currently the code which i have is generating the properties like

private int integerProperty  
         { 
            get  
            { 
                return integerField; 
            }
            set  
            { 
                integerField = value; 
            } 
        } 

I wanted the properties to be simple like...

private int integerProperty  
         { 
            get;              
            set; 
         } 

The code i have with me is

 CodeMemberProperty property1 = new CodeMemberProperty();
        property1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField")));
        property1.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField"),new CodePropertySetValueReferenceExpression()));
        type1.Members.Add(property1);

Anyone please help. Thanks in advance.

like image 425
suman Avatar asked Dec 03 '12 07:12

suman


2 Answers

As Botz3000 mentioned, it's officially not possible. However, with the following hack you can implement it:

var field = new CodeMemberField
  {
      Attributes = MemberAttributes.Public | MemberAttributes.Final,
      Name = "MyProperty",
      Type = new CodeTypeReference(typeof(MyType)),
  };

  field.Name += " { get; set; }";

By appending { get; set; } to the field name, it will generate a property in the actual source code.

like image 106
Wouter de Kort Avatar answered Sep 30 '22 15:09

Wouter de Kort


This is an old question, but is worth noting that the answer by "@Serguei Fedorov" is no longer applies (it's valid only for c# 1.0 to c# 2.0)

The solution of replacing "};" with "}" should be avoid, because "};" is used for the syntax of Object and Collection Initializers starting from C# 3.0.

Review Object and Collection Initializers.

Example:

 var pet = new { Age = 10, Name = "Fluffy" };  //it's ended by "};"

Alternative solution

You can use the new .NET Compiler Platform ("Roslyn") which support C# 1.0 to c#6.0.

The samples include ConvertToAutoProperty - A code refactoring to change a simple property with a trivial getter and setter into an auto property.

If you interested by CodeDom, there's a new CodeDOM Providers for .NET Compiler Platform (“Roslyn”) that can be installed from nuget

like image 33
M.Hassan Avatar answered Sep 30 '22 17:09

M.Hassan