public void Run(RefactoringContext context) { VariableInitializer initializer; var eventDeclaration = GetEventDeclaration(context, out initializer); var type = context.Resolve(eventDeclaration.ReturnType).Type; if (type == null) { return; } var invokeMethod = type.GetDelegateInvokeMethod(); if (invokeMethod == null) { return; } bool hasSenderParam = false; IEnumerable <IParameter> pars = invokeMethod.Parameters; if (invokeMethod.Parameters.Any()) { var first = invokeMethod.Parameters [0]; if (first.Name == "sender" /*&& first.Type == "System.Object"*/) { hasSenderParam = true; pars = invokeMethod.Parameters.Skip(1); } } const string handlerName = "handler"; var arguments = new List <Expression> (); if (hasSenderParam) { arguments.Add(new ThisReferenceExpression()); } foreach (var par in pars) { arguments.Add(new IdentifierExpression(par.Name)); } var methodDeclaration = new MethodDeclaration() { Name = "On" + initializer.Name, ReturnType = new PrimitiveType("void"), Modifiers = ICSharpCode.NRefactory.Cpp.Modifiers.Protected | ICSharpCode.NRefactory.Cpp.Modifiers.Virtual, Body = new BlockStatement() { new VariableDeclarationStatement(context.CreateShortType(eventDeclaration.ReturnType), handlerName, new MemberReferenceExpression(new ThisReferenceExpression(), initializer.Name)), new IfElseStatement() { Condition = new BinaryOperatorExpression(new IdentifierExpression(handlerName), BinaryOperatorType.InEquality, new PrimitiveExpression(null)), TrueStatement = new ExpressionStatement(new InvocationExpression(new IdentifierExpression(handlerName), arguments)) } } }; foreach (var par in pars) { var typeName = context.CreateShortType(par.Type); var decl = new ParameterDeclaration(typeName, par.Name); methodDeclaration.Parameters.Add(decl); } using (var script = context.StartScript()) { script.InsertWithCursor("Create event invocator", methodDeclaration, Script.InsertPosition.After); } }