3

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.

Marc Newlin
  • 63
  • 1
  • 3
  • 1
    How are you specifying the type in the code dom currently? – Kirk Woll Aug 17 '12 at 21:52
  • 1
    CodeDom provides no option to alter the text it emits. Unless you write your own provider or post-process the text. – Hans Passant Aug 17 '12 at 21:59
  • what is your goal? what for do you perform this? CodeDomProvider is for generating assemblies, in both cases resuls are equal – abatishchev Aug 18 '12 at 18:54
  • The case where using CLR types is a problem is when declaring an enum with a base type. For example, the generated code is "enum : UInt32" instead of "enum : uint". – Marc Newlin Aug 18 '12 at 20:52

1 Answers1

0

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.)

Vitali Kaspler
  • 1,340
  • 10
  • 16