Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 657955
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:52:51+00:00 2026-05-13T22:52:51+00:00

I am trying create a delegate representation of constructor by emitting a Dynamic Method,

  • 0

I am trying create a delegate representation of constructor by emitting a Dynamic Method, which has to match this very “loosely-typed” signature so it can be used with any kind of parametrized constructor:

public delegate Object ParamsConstructorDelegate(params object[] parameters);

and the code for this creating the delegate looks like (note this is for Silverlight)

public static ParamsConstructorDelegate CreateDelegate(ConstructorInfo constructor)
    {
        Guard.ArgumentNotNull(constructor, "constructor");
        Guard.ArgumentValue(constructor.GetParameters().Length == 0, MUSTBE_PARAMETERIZED_CONSTRUCTOR);

        var _argumentTypes = new Type[] { typeof(object[]) };
        var _parameters = constructor.GetParameters();
        var _parameterTypes = _parameters.Select((p) => p.ParameterType).ToArray();

        var _sourceType = constructor.DeclaringType;
        var _method = new DynamicMethod(constructor.Name, _sourceType, _argumentTypes);
        var _gen = _method.GetILGenerator();

        for (var _i = 0; _i < _parameters.Length; _i++)
        {
            if (_parameters[_i].IsOut || _parameterTypes[_i].IsByRef)
            {
                if (_i < 128)
                {
                    _gen.Emit(OpCodes.Ldarga_S, (byte)_i);
                }
                else
                    _gen.Emit(OpCodes.Ldarga, _i);
            }
            else
            {
                switch (_i)
                {
                    case 0:
                        _gen.Emit(OpCodes.Ldarg_0, _i);
                        break;
                    case 1:
                        _gen.Emit(OpCodes.Ldarg_1, _i);
                        break;
                    case 2:
                        _gen.Emit(OpCodes.Ldarg_2, _i);
                        break;
                    case 3:
                        _gen.Emit(OpCodes.Ldarg_3, _i);
                        break;
                    default:
                        if (_i < 128)
                            _gen.Emit(OpCodes.Ldarg_S, (byte)_i);
                        else
                            _gen.Emit(OpCodes.Ldarg, _i);
                        break;
                }
            }
        }
        _gen.Emit(OpCodes.Newobj, constructor);
        _gen.Emit(OpCodes.Ret); ;

        return (ParamsConstructorDelegate)_method.CreateDelegate(typeof(ParamsConstructorDelegate));
    }

Now, I’m getting a “Operation could destabilize the runtime.” verification exception, obviously the IL is wrong, so I hoping someone could correct me.

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T22:52:51+00:00Added an answer on May 13, 2026 at 10:52 pm

    I can see two problems; firstly you don’t need the _i for the Ldarg_0 thru Ldarg_3 cases (it is implicit). Secondly – your delegate only has one arg (the array). You’re going to need to get the items out of the array and cast – something like below (which handles pass-by-value only; for ref / out you’ll have to define a local and use stloc / ldloca / etc):

    using System;
    using System.Reflection.Emit;
    public delegate object ParamsConstructorDelegate(params object[] parameters);
    public class Foo
    {
        string s;
        int i;
        float? f;
        public Foo(string s, int i, float? f)
        {
            this.s = s;
            this.i = i;
            this.f = f;
        }
    }
    
    static class Program
    {
        static void Main()
        {
            var ctor = Build(typeof(Foo));
            Foo foo1 = (Foo)ctor("abc", 123, null);
            Foo foo2 = (Foo)ctor(null, 123, 123.45F);
        }
        static ParamsConstructorDelegate Build(Type type)
        {
            var mthd = new DynamicMethod(".ctor", type,
                new Type[] { typeof(object[]) });
            var il = mthd.GetILGenerator();
            var ctor = type.GetConstructors()[0]; // not very robust, but meh...
            var ctorParams = ctor.GetParameters();
            for (int i = 0; i < ctorParams.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_0);
                switch (i)
                {
                    case 0: il.Emit(OpCodes.Ldc_I4_0); break;
                    case 1: il.Emit(OpCodes.Ldc_I4_1); break;
                    case 2: il.Emit(OpCodes.Ldc_I4_2); break;
                    case 3: il.Emit(OpCodes.Ldc_I4_3); break;
                    case 4: il.Emit(OpCodes.Ldc_I4_4); break;
                    case 5: il.Emit(OpCodes.Ldc_I4_5); break;
                    case 6: il.Emit(OpCodes.Ldc_I4_6); break;
                    case 7: il.Emit(OpCodes.Ldc_I4_7); break;
                    case 8: il.Emit(OpCodes.Ldc_I4_8); break;
                    default: il.Emit(OpCodes.Ldc_I4, i); break;
                }
                il.Emit(OpCodes.Ldelem_Ref);
                Type paramType = ctorParams[i].ParameterType;
                il.Emit(paramType.IsValueType ? OpCodes.Unbox_Any
                    : OpCodes.Castclass, paramType);
            }
            il.Emit(OpCodes.Newobj, ctor);
            il.Emit(OpCodes.Ret);
            return (ParamsConstructorDelegate)
                mthd.CreateDelegate(typeof(ParamsConstructorDelegate));
        }
    }
    

    For info – I’m lazy – if I want to know what IL to write I write it in C# and then load it into reflector. For example, to do this I wrote a method:

    static object CreateFoo(object[] vals)
    {
        return new Foo((string)vals[0], (int)vals[1], (float?)vals[2]);
    }
    

    and reversed it from there

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 418k
  • Answers 418k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Here's the minimal edit I can thing of for the… May 15, 2026 at 9:54 am
  • Editorial Team
    Editorial Team added an answer In that case, your better choice is using JSON. It… May 15, 2026 at 9:54 am
  • Editorial Team
    Editorial Team added an answer You can delay your ScrollIntoView call using a Dispatcher.BeginInvoke with… May 15, 2026 at 9:54 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.