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.

3
  • grep the codebase? Which version of Visual Studio? Commented Sep 18, 2014 at 13:21
  • 1
    maybe a simple regex like "static \w+(" may help finding Commented Sep 18, 2014 at 13:21
  • @HimBromBeere: using \w is actually simpler and covers more cases. I updated my answer in this direction. Thx Commented Sep 18, 2014 at 13:28

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.