none
TypeBuilder DefineMethodOverride and IComparable<> RRS feed

  • Question

  • I'm trying to emit a class that implements IComparable<>. I keep getting an exception when calling CreateType(). The Exception says "Method CompareTo does not have an implementation". Here is the method I am using to emit the CompareTo method.

    _typeBuilder.AddInterfaceImplementation(typeof(IComparable<>).MakeGenericType(_typeBuilder)); const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; var method = _typeBuilder.DefineMethod("CompareTo", methodAttributes, CallingConventions.Standard, typeof(Int32), new Type[] { _typeBuilder });

    method.SetReturnType(typeof(Int32));
    method.SetParameters(_typeBuilder);
    ParameterBuilder obj = method.DefineParameter(1, ParameterAttributes.None, "other");
    ILGenerator gen = method.GetILGenerator();

    gen.Emit(OpCodes.Ret);

    var mi = TypeBuilder.GetMethod(typeof(IComparable<>).MakeGenericType(_typeBuilder), typeof(IComparable<>).GetMethod("CompareTo"));

    _typeBuilder.DefineMethodOverride(method,mi);


    Any help would be appreciated.

    Thanks


    STBraley


    • Edited by STBraley Tuesday, August 6, 2013 4:02 PM
    Tuesday, August 6, 2013 3:59 PM

Answers

  • Hi STBraley,

    Thank you for posting in our MSDN Community, I will be working with you on this post.

    I use your code to build a project, I find nothing wrong, it works fine.

    Could you please send out the complete source of  the project. We only need a simple sample to reproduce the problem. You can remove any confidential information or business logic from it.

    I look forward to hearing from you.

    Best Regards,

    • Marked as answer by STBraley Wednesday, August 7, 2013 12:41 PM
    Wednesday, August 7, 2013 5:46 AM
    Moderator

All replies

  • Hi STBraley,

    Thank you for posting in our MSDN Community, I will be working with you on this post.

    I use your code to build a project, I find nothing wrong, it works fine.

    Could you please send out the complete source of  the project. We only need a simple sample to reproduce the problem. You can remove any confidential information or business logic from it.

    I look forward to hearing from you.

    Best Regards,

    • Marked as answer by STBraley Wednesday, August 7, 2013 12:41 PM
    Wednesday, August 7, 2013 5:46 AM
    Moderator
  • Thank you. After your response, i found the problem in a base class that the emitted class was using. 


    STBraley

    Wednesday, August 7, 2013 12:42 PM