Page 2 of 10               << Previous  1  2  3  4  5  6  7  8  9  10  Next >>


Custom FxCop Rule - Do not call .NET Garbage Collector

Here is the CSharp source code for a custom FxCop rule to enforce not calling the .NET Garbage Collector directly from code. This rule, named DoNotCallGarbageCollectorDirectly inherits from the BaseMigrationControlFlowRule class and calls the VisitCall method.

If you create a small VB.NET sample program to call the .NET Framework's Garbage Collector, build the code, and examine the MSIL, you will see calls to:


So, we can create an FxCop rule that looks for calls to System.GC which is the class. We do not need to look for the particular methods.

Sample VB.NET code to call the garbage collector:

          Dim totMem As Long = GC.GetTotalMemory(True)
          Dim colCount As Integer = GC.CollectionCount(0)

C# code for custom FxCop rule:

using System;
using Microsoft.Cci;
using Microsoft.Fugue;
using Microsoft.FxCop.Sdk;
using Microsoft.FxCop.Sdk.Introspection;

public class DoNotCallGarbageCollectorDirectly : BaseMigrationControlFlowRule
    public DoNotCallGarbageCollectorDirectly() : base("DoNotCallGarbageCollectorDirectly")

    public override void VisitCall(Variable destination, 
               Variable receiver, Method callee, ExpressionList arguments, 
               bool isVirtualCall, IProgramContext programContext, 
               IExecutionState stateBeforeInstruction, 
               IExecutionState stateAfterInstruction)
        if (callee.DeclaringType.FullName.Trim().ToUpper().Equals("SYSTEM.GC"))
            base.Problems.Add(new Problem(GetResolution(), programContext));
        base.VisitCall(destination, receiver, callee, arguments, 
                isVirtualCall, programContext, stateBeforeInstruction, 

Rule definition in the XML rules file:

<Rule TypeName="DoNotCallGarbageCollectorDirectly" 
          Category="VBMigration" CheckId="AA1001">
        Do not call Garbage Collector directly
        Calls to the Garbage Collector directly are not advised.
        Do not call Garbage Collector directly. To ensure objects are 
        disposed of properly, use the Using KeyWord.
    <MessageLevel Certainty="99">
    <Owner />

The XML rules file is mostly self explanatory. You have the rule name which must match the class name, category the rule falls in so FxCop can group the results of its analysis, a certainty level, which in this case is set high since we can positively identify GC calls, and a recommended resolution. The CheckId is a unique id for the rule. Each rule must have a different CheckId.


Page 2 of 10               << Previous  1  2  3  4  5  6  7  8  9  10  Next >>

About TheScarms
About TheScarms

Sample code
version info

If you use this code, please mention ""

Email this page

© Copyright 2019 TheScarms
Goto top of page