Search code examples
c#reflectionreflection.emit

How do I emit a call to [mscorlib]System.Console::Write(char)?


I am currently emitting a call to [mscorlib]System.Console::Write(char) as follows:

ilg.EmitCall(OpCodes.Call,
             typeof(Console).GetMethods().First(m =>
                 m.Name == "Write" && m.GetParameters().Length == 1 &&
                 m.GetParameters().Any(p => p.ParameterType == typeof(char))),
             null);

But is there a cleaner way on how I can reference the Console.Write(char) method, possibly without actually iterating through the formal arguments?


Solution

  • Try using GetMethod, rather than GetMethods:

    ilg.EmitCall(OpCodes.Call, 
      typeof(Console).GetMethod("Write", new[] { typeof(char) }),
      null);