Using C# reflection to call a constructor

I don’t think GetMethod will do it, no – but GetConstructor will. using System; using System.Reflection; class Addition { public Addition(int a) { Console.WriteLine(“Constructor called, a={0}”, a); } } class Test { static void Main() { Type type = typeof(Addition); ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) }); object instance = ctor.Invoke(new object[] { 10 }); … Read more

‘UserControl’ constructor with parameters in C#

Design decisions made regarding the way Windows Forms works more or less preclude parameterized .ctors for windows forms components. You can use them, but when you do you’re stepping outside the generally approved mechanisms. Rather, Windows Forms prefers initialization of values via properties. This is a valid design technique, if not widely used. This has … Read more

How to use base class’s constructors and assignment operator in C++?

You can explicitly call constructors and assignment operators: class Base { //… public: Base(const Base&) { /*…*/ } Base& operator=(const Base&) { /*…*/ } }; class Derived : public Base { int additional_; public: Derived(const Derived& d) : Base(d) // dispatch to base copy constructor , additional_(d.additional_) { } Derived& operator=(const Derived& d) { Base::operator=(d); … Read more

Calling an async method from a constructor in Dart

Probably the best way to handle this is with a factory function, which calls a private constructor. In Dart, private methods start with an underscore, and “additional” constructors require a name in the form ClassName.constructorName, since Dart doesn’t support function overloading. This means that private constructors require a name, which starts with an underscore (MyComponent._create … Read more

Static class initializer in PHP

Sounds like you’d be better served by a singleton rather than a bunch of static methods class Singleton { /** * * @var Singleton */ private static $instance; private function __construct() { // Your “heavy” initialization stuff here } public static function getInstance() { if ( is_null( self::$instance ) ) { self::$instance = new self(); … Read more

Horrendous performance & large heap footprint of Java 8 constructor reference?

In the first case (ArrayList::new) you are using the constructor which takes an initial capacity argument, in the second case you are not. A large initial capacity (index in your code) causes a large Object[] to be allocated, resulting in your OutOfMemoryErrors. Here are the two constructors’ current implementations: public ArrayList(int initialCapacity) { if (initialCapacity … Read more