Skip to content

Instantly share code, notes, and snippets.

@jfrijters
Created April 8, 2014 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfrijters/10151709 to your computer and use it in GitHub Desktop.
Save jfrijters/10151709 to your computer and use it in GitHub Desktop.
typeof(Foo).GetMethod("Foo") optimization
diff --git a/Src/Compilers/CSharp/Source/Lowering/LocalRewriter/LocalRewriter_Call.cs b/Src/Compilers/CSharp/Source/Lowering/LocalRewriter/LocalRewriter_Call.cs
index d356dec..3ad67f5 100644
--- a/Src/Compilers/CSharp/Source/Lowering/LocalRewriter/LocalRewriter_Call.cs
+++ b/Src/Compilers/CSharp/Source/Lowering/LocalRewriter/LocalRewriter_Call.cs
@@ -130,6 +130,35 @@ namespace Microsoft.CodeAnalysis.CSharp
{
Debug.Assert(node != null);
+ if (node.ReceiverOpt is BoundTypeOfOperator && node.Method.Name == "GetMethod" && !node.Method.IsExtensionMethod)
+ {
+ TypeSymbol type = (TypeSymbol)((BoundTypeOfOperator)node.ReceiverOpt).SourceType.ExpressionSymbol;
+ if (type.IsFromCompilation(compilation))
+ {
+ switch (node.Method.ParameterCount)
+ {
+ // Type.GetMethod(string)
+ case 1:
+ BoundExpression arg = node.Arguments[0];
+ if (arg.Type.IsStringType() && arg.ConstantValue != null)
+ {
+ string methodName = arg.ConstantValue.StringValue;
+ ImmutableArray<MethodSymbol> methods = type.GetMembers()
+ .OfType<MethodSymbol>()
+ .Where(m => m.DeclaredAccessibility == Accessibility.Public
+ && m.MethodKind == MethodKind.Ordinary
+ && m.MetadataName == methodName)
+ .ToImmutableArray();
+ if (methods.Length == 1)
+ {
+ return factory.MethodInfo(methods[0]);
+ }
+ }
+ break;
+ }
+ }
+ }
+
// Rewrite the receiver
BoundExpression rewrittenReceiver = VisitExpression(node.ReceiverOpt);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment