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 6207695
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T05:40:42+00:00 2026-05-24T05:40:42+00:00

Say I have a SpaceShip class, like so: public class SpaceShip { public SpaceShip()

  • 0

Say I have a SpaceShip class, like so:

public class SpaceShip {
    public SpaceShip() {  }
    public SpaceShip(IRocketFuelSource fuelSource) {  }
}

I want to use TypeBuilder to create a type at run-time which inherits from SpaceShip, and defines one constructor for each of the ones in SpaceShip. I don’t need the constructors to actually do anything except pass their arguments up to the parent (“pass-through” constructors). For example, the generated type would look something like this if expressed in C#:

public class SpaceShipSubClass : SpaceShip {
    public SpaceShipSubClass() : base() {  }
    public SpaceShipSubClass(IRocketFuelSource fuelSource) : base(fuelSource) {  }
}

To complicate things a bit, I don’t actually know which class the generated type will be inheriting from until run-time (so I’ll have to take into account any number of constructors, possibly with default parameters).

Is this possible? I think I could figure it out if I had a general direction to start with, it’s just that I’m completely new to TypeBuilder.

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-24T05:40:43+00:00Added an answer on May 24, 2026 at 5:40 am

    Alright, I couldn’t find anything online, so I ended up implementing my own. This should help start off anyone writing some sort of proxy, too.

    public static class TypeBuilderHelper
    {
        /// <summary>Creates one constructor for each public constructor in the base class. Each constructor simply
        /// forwards its arguments to the base constructor, and matches the base constructor's signature.
        /// Supports optional values, and custom attributes on constructors and parameters.
        /// Does not support n-ary (variadic) constructors</summary>
        public static void CreatePassThroughConstructors(this TypeBuilder builder, Type baseType)
        {
            foreach (var constructor in baseType.GetConstructors()) {
                var parameters = constructor.GetParameters();
                if (parameters.Length > 0 && parameters.Last().IsDefined(typeof(ParamArrayAttribute), false)) {
                    //throw new InvalidOperationException("Variadic constructors are not supported");
                    continue;
                }
    
                var parameterTypes = parameters.Select(p => p.ParameterType).ToArray();
                var requiredCustomModifiers = parameters.Select(p => p.GetRequiredCustomModifiers()).ToArray();
                var optionalCustomModifiers = parameters.Select(p => p.GetOptionalCustomModifiers()).ToArray();
    
                var ctor = builder.DefineConstructor(MethodAttributes.Public, constructor.CallingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
                for (var i = 0; i < parameters.Length; ++i) {
                    var parameter = parameters[i];
                    var parameterBuilder = ctor.DefineParameter(i + 1, parameter.Attributes, parameter.Name);
                    if (((int)parameter.Attributes & (int)ParameterAttributes.HasDefault) != 0) {
                        parameterBuilder.SetConstant(parameter.RawDefaultValue);
                    }
    
                    foreach (var attribute in BuildCustomAttributes(parameter.GetCustomAttributesData())) {
                        parameterBuilder.SetCustomAttribute(attribute);
                    }
                }
    
                foreach (var attribute in BuildCustomAttributes(constructor.GetCustomAttributesData())) {
                    ctor.SetCustomAttribute(attribute);
                }
    
                var emitter = ctor.GetILGenerator();
                emitter.Emit(OpCodes.Nop);
    
                // Load `this` and call base constructor with arguments
                emitter.Emit(OpCodes.Ldarg_0);
                for (var i = 1; i <= parameters.Length; ++i) {
                    emitter.Emit(OpCodes.Ldarg, i);
                }
                emitter.Emit(OpCodes.Call, constructor);
    
                emitter.Emit(OpCodes.Ret);
            }
        }
    
    
        private static CustomAttributeBuilder[] BuildCustomAttributes(IEnumerable<CustomAttributeData> customAttributes)
        {
            return customAttributes.Select(attribute => {
                var attributeArgs = attribute.ConstructorArguments.Select(a => a.Value).ToArray();
                var namedPropertyInfos = attribute.NamedArguments.Select(a => a.MemberInfo).OfType<PropertyInfo>().ToArray();
                var namedPropertyValues = attribute.NamedArguments.Where(a => a.MemberInfo is PropertyInfo).Select(a => a.TypedValue.Value).ToArray();
                var namedFieldInfos = attribute.NamedArguments.Select(a => a.MemberInfo).OfType<FieldInfo>().ToArray();
                var namedFieldValues = attribute.NamedArguments.Where(a => a.MemberInfo is FieldInfo).Select(a => a.TypedValue.Value).ToArray();
                return new CustomAttributeBuilder(attribute.Constructor, attributeArgs, namedPropertyInfos, namedPropertyValues, namedFieldInfos, namedFieldValues);
            }).ToArray();
        }
    }
    

    Usage (assuming you have a TypeBuilder object — see here for an example):

    var typeBuilder = ...;  // TypeBuilder for a SpaceShipSubClass
    typeBuilder.CreatePassThroughConstructors(typeof(SpaceShip));
    var subType = typeBuilder.CreateType();  // Woo-hoo, proxy constructors!
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Lets say have this immutable record type: public class Record { public Record(int x,
Say I have a class named Frog, it looks like: public class Frog {
Say I have a LINQ-to-XML query that generates an anonymous type like this: var
Say I have an Intent like this: Intent intent = new Intent(context, MyActivity.class); I
let say have element like this <div class=watch-me style=display: none;>Watch Me Please</div> as we
Say I have a public method1 calling a private method2 , I use a
Say I have the controller as follows: public class Controller { ISomeService _service; public
Say have normal class in iOS, called A. I'd like to pass this as
Say I have this little bit of code: public static void LoadSomething(Type t) {
Let's say I have these classes : Vehicle, Car and Spaceship: class Vehicle{ void

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.