#nullable enable using System; using System.Reflection; namespace GlitchyEngine.Extensions; public static class ActivatorExtension { /// Creates an instance of the specified type using that type's default constructor. /// The type of object to create. /// A reference to the newly created object; or if no instance could be created. public static object? CreateInstanceSafe(Type type) { try { return Activator.CreateInstance(type, true); } catch (MissingMethodException e) { Log.Error($"Failed to create instance of type \"{type}\": The type doesn't contain a constructor with zero parameters.\nMake sure the type has a constructor that takes no arguments (It can be private!).\n{e}"); } catch (MethodAccessException e) { Log.Error($"Failed to create instance of type \"{type}\": The default constructor is not accessible.\n{e}"); } catch (Exception e) { Log.Error($"Failed to create instance of type \"{type}\": {e}"); } return null; } /// Creates an instance of the specified type using a constructor that matches the given arguments. /// The type of object to create. /// The arguments passed to the constructor /// A reference to the newly created object; or if no instance could be created. public static object? CreateInstanceSafe(Type type, params object[] args) { try { return Activator.CreateInstance(type, BindingFlags.Default | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.CreateInstance | BindingFlags.Instance, null, args, null); } catch (Exception e) { Log.Error($"Failed to create instance of type \"{type}\": {e}"); } return null; } }