using System; using System.Collections.Generic; using System.Text; using System.IO; using System.CodeDom; using System.CodeDom.Compiler; namespace BugInCodeComGenerateEvent { class Program { static void Main(string[] args) { string strGeneratedCode = null; System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); System.CodeDom.Compiler.CodeDomProvider provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); CodeNamespace ns = new CodeNamespace("Bug"); ccu.Namespaces.Add(ns); //Create a new Class A CodeTypeDeclaration ctdA = new CodeTypeDeclaration("A"); ns.Types.Add(ctdA); //Create a new Event TestEvent in A CodeMemberEvent cmeATestEvent = new CodeMemberEvent(); cmeATestEvent.Name = "TestEvent"; cmeATestEvent.Type = new CodeTypeReference(typeof(EventHandler)); cmeATestEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final; ctdA.Members.Add(cmeATestEvent); //Create a new Class B (Inherits from A) CodeTypeDeclaration ctdB = new CodeTypeDeclaration("B"); ctdB.Attributes = MemberAttributes.Public | MemberAttributes.Final; ctdB.BaseTypes.Add("A"); ns.Types.Add(ctdB); //Create a new Event TestEvent in B CodeMemberEvent cmeBTestEvent = new CodeMemberEvent(); cmeBTestEvent.Name = "TestEvent"; cmeBTestEvent.Type = new CodeTypeReference(typeof(System.ComponentModel.CancelEventHandler)); cmeBTestEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.New; cmeBTestEvent.Comments.Add(new CodeCommentStatement("public event EventHandler TestEvent; is wrong (new-Attribute is missing)")); cmeBTestEvent.Comments.Add(new CodeCommentStatement("public new event EventHandler TestEvent; would be correct")); ctdB.Members.Add(cmeBTestEvent); /* * Have a look at: Class: Microsoft.CSharp.CSharpCodeGenerator * * Compare Methods: GenerateMethod with GenerateEvent * * GenerateMethod calls: * * this.OutputMemberAccessModifier(e.Attributes); (public / internal protected ....) this.OutputVTableModifier(e.Attributes); (new ) this.OutputMemberScopeModifier(e.Attributes); (abstract / virtual ....) * * GenerateEvent only calls: * * this.OutputMemberAccessModifier(e.Attributes); (public / internal protected ....) * * --- Calls to OutputVTableModifier and OutputMemberScopeModifier are missing */ using (MemoryStream ms = new MemoryStream()) { IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(ms)); // Generate source code using the code generator. provider.GenerateCodeFromCompileUnit(ccu, tw, new CodeGeneratorOptions()); // Close the output file. tw.Close(); strGeneratedCode = System.Text.Encoding.UTF8.GetString(ms.GetBuffer()); } System.Diagnostics.Debug.WriteLine(strGeneratedCode); Console.WriteLine(strGeneratedCode); } } }