gendarme icon indicating copy to clipboard operation
gendarme copied to clipboard

[Patch] DeclareEventsExplicitlyRule raised on generated code

Open troberson opened this issue 13 years ago • 1 comments

The DeclareEventsExplicitlyRule is raised when using a lambda expression for an event. using System;

sealed class Test
{
        class TestEventArgs : EventArgs
        {
                public TestEventArgs (int x)
                {
                        this.X = x;
                }

                public int X { get; private set; }
        }

        event EventHandler<TestEventArgs> TestEvent;

        public Test ()
        {
                TestEvent += (o,e) => Console.WriteLine ("Test: {0}", e.X); // <-------- Gendarme complains about this line

                if (TestEvent != null)
                        TestEvent (this, new TestEventArgs (42));
        }

        static void Main ()
        {
                new Test ();
        }
}

3. DeclareEventsExplicitlyRule

Problem: An event handler was declared without the 'event' keyword
* Severity: High, Confidence: High
* Target:   Test
* Location: System.EventHandler`1<Test/TestEventArgs> Test::<>f__am$cache0

Solution: Add the missing 'event' keyword to your event handler declaration
More info available at: https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Correctness.DeclareEventsExplicitlyRule(2.10)

troberson avatar Jan 25 '12 19:01 troberson

Here is a patch to correct the issue by testing for IsGeneratedCode() on the type and member:

diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs
index 442572e..ad04b73 100644
--- a/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs
+++ b/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs
@@ -29,6 +29,7 @@
 using Mono.Cecil;

 using Gendarme.Framework;
+using Gendarme.Framework.Rocks;

 namespace Gendarme.Rules.Correctness {

@@ -70,12 +71,15 @@ namespace Gendarme.Rules.Correctness {

        public RuleResult CheckType (TypeDefinition type)
        {
-           if (!type.HasFields || type.IsEnum)
+           if (!type.HasFields || type.IsEnum || type.IsGeneratedCode ())
                return RuleResult.DoesNotApply;

            // allow to short-circuit LookForEvent if the type has no event
            bool has_events = type.HasEvents;
            foreach (FieldDefinition field in type.Fields) {
+               if (field.IsGeneratedCode ())
+                   continue;
+
                TypeReference ftype = field.FieldType;
                if (ftype.Namespace != "System")
                    continue;

troberson avatar Jan 25 '12 19:01 troberson