-1

Could someone help me to override ToString() method?

The C# code I want to build is as follows:

  public override string ToString()
  {
        return $"{Id}, {Description}, {ParentId}";
  }

The code I made to emit is as follows:

MethodBuilder toStringMethod = typebuilder.DefineMethod("ToString", 
MethodAttributes.Public | MethodAttributes.HideBySig | 
MethodAttributes.NewSlot | MethodAttributes.Virtual | 
MethodAttributes.Final,    CallingConventions.HasThis, typeof(string), 
Type.EmptyTypes);

ILGenerator il = toStringMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, "{0},{1},{2}");
il.Emit(OpCodes.Ldc_I4_4);
il.Emit(OpCodes.Call, getIdMethodeBuilder);
il.Emit(OpCodes.Call, getDescriptionMethodeBuilder);
il.Emit(OpCodes.Call, getParentIdMethodeBuilder);

il.Emit(OpCodes.Ret);
typebuilder.DefineMethodOverride(toStringMethod, typeof(object).GetMethod("ToString"));

Thanks in advance.

Joon w K
  • 777
  • 1
  • 6
  • 27
  • 1
    You're missing the call to `String.Format`. – Lasse V. Karlsen May 27 '17 at 05:17
  • @lasse But interpolation should work and that is what the OP is using. Am i missing something? – CodingYoshi May 27 '17 at 05:19
  • @CodingYoshi: interpolation is strictly a compile-time construct, i.e. syntactic sugar. The compiler generates a call to `String.Format`. There's nothing in the IL that relates to interpolated strings. – Peter Duniho May 27 '17 at 05:20
  • @PeterDuniho Got it. Thanks. – CodingYoshi May 27 '17 at 05:23
  • Your mistake appears to be a simple typographical error, i.e. you forgot to include the call to `String.Format()`, as the first comment above says. That said, note that the string you are generating is not the same as the string in your C# version of the `ToString()` override. I.e. the former has no spaces, while the latter has a space after each of the two commas. – Peter Duniho May 27 '17 at 05:27
  • Thanks for comments. When I 'm available I will try those and share the outcome with you. Thanks a lot. – Joon w K May 28 '17 at 07:01

1 Answers1

1

Thanks to @lasse. I got my code corrected as follows:

  Type[] formatStringArgs = { typeof(string), typeof(int), typeof(string), typeof(int) };
   MethodInfo formatString = typeof(String).GetMethod("Format", formatStringArgs);

   il = toStringMethod.GetILGenerator();
   il.Emit(OpCodes.Nop);
   il.Emit(OpCodes.Ldstr, "{0},{1},{2}");

   il.Emit(OpCodes.Ldarg_0);
   il.Emit(OpCodes.Call, getIdMethodeBuilder);
   il.Emit(OpCodes.Box, typeof(Int32));

   il.Emit(OpCodes.Ldarg_0);                   
   il.Emit(OpCodes.Call, getDescriptionMethodeBuilder);

   il.Emit(OpCodes.Ldarg_0);
   il.Emit(OpCodes.Call, getParentIdMethodeBuilder);
   il.Emit(OpCodes.Box, typeof(Int32));

   il.Emit(OpCodes.Call, formatString);
   il.Emit(OpCodes.Ret);
   typebuilder.DefineMethodOverride(toStringMethod, 
   typeof(object).GetMethod("ToString"));

Thanks all.

Joon w K
  • 777
  • 1
  • 6
  • 27