user376591
user376591

Reputation:

set name on method arguments

I am using Reflection.Emit to make a exe. I have come so far that I can create a working CIL PE. (It just output a string to Console.WriteLine.) But the argument to main method is automaticly generated (A_0).

.method public static void  Main(string[] A_0) cil managed
{
  .entrypoint
  // Code size       12 (0xc)
  .maxstack  1
  IL_0000:  nop
  IL_0001:  ldstr      "Cafe con pan"
  IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000b:  ret
} // end of method Program::Main

contrast it with the code from a corresponding C# program

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       13 (0xd)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "Cafe con pan"
  IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000b:  nop
  IL_000c:  ret
} // end of method Program::Main

the argument name is args. How can I give name to the argument? The code I use for making the method look like this:

Il = System.reflection.Emit
Re = System.Reflection
tb = Reflection.Emit.TypeBuilder

Il.MethodBuilder meth = tb.DefineMethod(
                "Main", // name
                Re.MethodAttributes.Public | Re.MethodAttributes.Static,
                // method attributes
                typeof(void),   // return type
                new Type[] { typeof(String[]) }); // parameter types

Il.ILGenerator methIL = meth.GetILGenerator();
methIL.Emit(Il.OpCodes.Nop);
methIL.Emit(Il.OpCodes.Ldstr, "Cafe con pan");
Type [] args = new Type []{typeof(string)};
Re.MethodInfo printString = typeof(Console).GetMethod("WriteLine", args);
methIL.Emit(Il.OpCodes.Call, printString);
methIL.Emit(Il.OpCodes.Ret);

I have checked the TypeBuilder.DefineMethod documentation for any clue to do that as it is the logical place to have such an info but with no avail.
Do anyone have a suggestion?

Upvotes: 3

Views: 1113

Answers (1)

AakashM
AakashM

Reputation: 63348

Looks like MethodBuilder.DefineParameter allows you to specify parameter names:

Sets the parameter attributes and the name of a parameter of this method, or of the return value of this method. Returns a ParameterBuilder that can be used to apply custom attributes.

Upvotes: 6

Related Questions