Query to find methods with parameters having default values

by Jason Haley 13. January 2011 19:56

Today I was in Bill Wagner’s talk on C# Puzzles and one of them got me thinking about writing a query for Reflector – to find a listing of all the methods that have default values set in them.

If you are using the .Net Reflector 7 Beta, you can import this query from this file: ListMethodsWithDefaultParameterValue.xml.  Otherwise you case use the query below:

from a in AssemblyManager.Assemblies.Cast<IAssembly>()
from m in a.Modules.Cast<IModule>()
from t in m.Types.Cast<ITypeDeclaration>()
from meth in t.Methods.Cast<IMethodDeclaration>()
where ((IMethodSignature)meth).Parameters.Count > 0
from prm in ((IMethodSignature)meth).Parameters.Cast<IParameterDeclaration>()
from ca in prm.Attributes.Cast<ICustomAttribute>()
where ((ITypeReference)ca.Constructor.DeclaringType).Name
== "DefaultParameterValueAttribute"
select meth

Here are the save details I used so it would show in a listing that can be clicked on to take you to the method:

image

What it does:

Line 1:  Looks at all of the loaded assemblies loaded in Reflector at the time you run the query
Line 2:  Looks at all the modules in each assembly
Line 3:  Looks at all the types in each module
Line 4:  Looks at all the methods in each type
Line 5:  Filters out any methods that don’t have parameters
Line 6:  Looks at all the parameters in each of the methods
Line 7:  Looks at the attributes for each parameter
Line 8: Casts the attribute to its type and checks its name to see if it is “DefaultParameterValueAttribute”
Line 9: Returns the IMethodDeclaration for the methods that have a match (this will bind to the linked list control – otherwise it will just output the name as text if you select the output window)

Comments (0) | Post RSSRSS comment feed |

Categories:
Tags:

Comments are closed