Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Analysis Warning 2214 - How best to fix?

Tags:

c#

I have the following code:

    public partial class AuditLog : IBusinessEntity
    {
        public BusinessEntityType EntityType { get { return BusinessEntityType.AuditLog; } }

        /// <summary>
        /// Constructor accepting parameter initialization arguments
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="entity"></param>
        /// <param name="command"></param>
        /// <param name="commandText"></param>
        public AuditLog(string userName, BusinessEntityType entity, AuditLogCommand command, string commandText)
        {
            this.Timestamp = DateTime.Now;
            this.UserName = userName;
            this.Entity = entity.ToString();
            this.Command = command.ToString();
            this.CommandText = commandText;
        }
    }

This is generating a CA2214 warning. The BusinessEntityType and AuditLogCommand method parameters are both enumerations. I don't see what the issue is here, and therefore am not certain how to satisfy the warning.

Thanks.

like image 591
Randy Minder Avatar asked Oct 18 '10 20:10

Randy Minder


1 Answers

Is one or more of your properties virtual ? Then that is why, since CA2214 is the "Do not call overridable methods in constructors" warning.

Here is the reasoning for the rule from MSDN:

When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed.

What this means is that if someone inherits from your class, and overrides a method or property that is accessed in your constructor - then the overriding implementation will be hit before the constructor for the inherited class has run. This might lead to problems if the overriding implementation relies on state set in the constructor.

To satisfy the warning, you need to make the properties and methods accessed in the constructor non-virtual (you could make the type sealed, if appropiate).

like image 87
driis Avatar answered Oct 13 '22 12:10

driis