Outputting C# aliases (int, etc) instead of CLR types (Int32, etc) using CodeDom / CSharpCodeProvider

345 Views Asked by At

When generating C# code using CodeDom / CSharpCodeProvider, is it possible to force the output to use C# aliases instead of CLR types where possible?

I am currently parsing the resulting C# code and replacing CLR types with their aliases, but I would like to find out if it is possible to do this during code generation.

1

There are 1 best solutions below

0
On

Microsoft.CSharp.CSharpCodeProvider by default generates code with C# aliases.

Example:

        CodeCompileUnit compileUnit = new CodeCompileUnit();
        CodeNamespace sampleNamespace = new CodeNamespace("Sample");

        CodeTypeDeclaration sampleClass = new CodeTypeDeclaration("SampleClass");
        sampleClass.IsClass = true;
        sampleClass.Members.Add(new CodeMemberField(typeof(Int32), "_sampleField"));

        CodeMemberProperty prop = new CodeMemberProperty();
        prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        prop.Name = "SampleProp";
        prop.HasGet = true;
        prop.Type = new CodeTypeReference(typeof(System.Int32));
        prop.GetStatements.Add(new CodeMethodReturnStatement(
    new CodeFieldReferenceExpression(
    new CodeThisReferenceExpression(), "_sampleField")));

        sampleClass.Members.Add(prop);
        sampleNamespace.Types.Add(sampleClass);
        compileUnit.Namespaces.Add(sampleNamespace);

        using (var fileStream = new StreamWriter(File.Create("outputfile.cs")))
        {
            var provider = new Microsoft.CSharp.CSharpCodeProvider();

            provider.GenerateCodeFromCompileUnit(compileUnit, fileStream, null);
        }

Will generate:

namespace Sample {

    public class SampleClass {

        private int _sampleField;

        public int SampleProp {
            get {
                return this._sampleField;
            }
        }
    }
}

As you can see, although I used typeof(Int32), it converted it to "int". (Int64 it converts to "long" etc.)