16

I have a large Visual Studio solution of many C# projects. How to find all the static constructors? We had a few bugs where some did silly things, I want to check the others.

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

4 Answers4

29

In Visual Studio you can search in code using a regular expression.

Try this one:

static\s+\w+\s*\(

search box

You may adjust the character set if you allow your developers to use other than letter, numbers and underscore. Simplified regex using \w

This works because other uses of the static keyword requires at least a return type.

Community
  • 1
  • 1
Steve B
  • 36,818
  • 21
  • 101
  • 174
4

I think using reflection is fastest way to achieve it. You can add new project to solution and write small piece of code (perhaps save constructor names to text file):

public static IEnumerable<ConstructorInfo> GetAllStaticConstructorsInSolution()
{
   var assemblies = AppDomain.CurrentDomain.GetAssemblies();

   return assemblies.SelectMany(assembly => assembly.DefinedTypes
                   .Where(type => type.DeclaredConstructors.Any(constructorInfo => constructorInfo.IsStatic))
                   .SelectMany(x => x.GetConstructors(BindingFlags.Static)))
                   .Distinct();
}

Above Linq query should work although I haven't tested it.

fex
  • 3,488
  • 5
  • 30
  • 46
1

You could try using reflection over the built assemblies rather than searching the source code: http://msdn.microsoft.com/en-us/library/h70wxday(v=vs.110).aspx This might be faster/easier than grepping the text.

You could also look at tools like NDepend: http://www.ndepend.com/ It will actually let you write linq queries over the code. It's not cheap, though.

JMarsch
  • 21,484
  • 15
  • 77
  • 125
1

You can use ildasm and dump the assembly, then search the .il file for .cctor (not .ctor, use the extra c). Static constructors are implemented with .cctor methods.

ildasm program.exe /out=program.il

Example:

.method private hidebysig specialname rtspecialname static
        void  .cctor() cil managed
{
  // Code size       13 (0xd)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "Static constructor"
  IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000b:  nop
  IL_000c:  ret
} // end of method Animal::.cctor
codenheim
  • 20,467
  • 1
  • 59
  • 80