Home > Enterprise >  C# (T)Activator.CreateInstance(typeof(T), param) calls parameterless constructor
C# (T)Activator.CreateInstance(typeof(T), param) calls parameterless constructor

Time:07-08

HexMap is an object created by Unity game engine. MonoBehaviour is base Unity class. Problem occurs when passing this object as a parameter.

public class HexMap : MonoBehaviour
{

}

public class A
{
    public A(){}
    public A(HexMap hexMap)
    {
    }
}
    
public class B : A
{
    public B(){}
    public B(HexMap hexMap) : base(hexMap)
    {
    }
}

// This object is created by Unity and found successfully
HexMap hexMap = Object.FindObjectOfType<HexMap>();
A a = (A)Activator.CreateInstance(typeof(B), hexMap);

Code above calls B parameterless constructor. How to make it call a constructor with a parameter?

CodePudding user response:

After the edits and providing your actual code I can tell you what the issue is - it is quite a tricky pitfall!

There are various overloads of Activator.CreateInstance. In specific

Now what is tricking you here is that UnityEngine.Object (which MonoBehaviour and basically all built-in class types derive from) has an implicit conversion operator to bool (also see source code) so the compiler is treating your hexMap as a bool parameter and therefore prefers the second overload which is a parameterless constructor. See also Which Method overload is chosen? for more details on the reasons.

To make clear for the compiler what you want to do you rather want to explicitely pass in

A a = (A)Activator.CreateInstance(typeof(B), new object[]{hexMap}); 

Little simulation of the issue: https://dotnetfiddle.net/x0YqYs

  • Related