Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all static constructors?

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.

like image 842
Colonel Panic Avatar asked Sep 18 '14 13:09

Colonel Panic


2 Answers

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.

like image 176
Steve B Avatar answered Oct 13 '22 09:10

Steve B


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.

like image 35
fex Avatar answered Oct 13 '22 11:10

fex