I want to create an array that holds different objects within an inheritance paradigm. I have an item class that several other classes to be inherited. My goal is to put different objects that inherit item into an array. I won't know the type of object and thus will need to instantiate an object of an unknown type.
I've been following this Stackoverflow question: Dynamically create an object of < Type> and different variations of it.
using System;
const int _size= 3;
private Item[] _slots = new Item[_size];
// Method to place objects in array
// item here may be Carrot or Potato or another object
public void AddToBackpack(Item item) {
// Dynamically create Item object
var newItem = GetInstance<Item>(item.ToString());
// Find object in _slots array of similar type and merge newItem with it.
}
public T GetInstance<T>(string type) {
return (T)Activator.CreateInstance(Type.GetType(type));
}
// Classes
public class Carrot : Item {
public Carrot() {
_stackLimit = 5;
}
}
public class Potato : Item {
public Potato() {
_stackLimit = 3;
}
}
public abstract class Item {
public int _stackLimit { get; set; } = 1;
public int _stackSize { get; set; } = 1;
}
Here is the error I'm getting when I try and and call Activator.CreateInstance
Run-time exception (line -1): Request failed.
Stack Trace:
[System.Security.SecurityException: Request failed.]
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Submission#0.GetInstance[T](String type)
at Submission#0.<<Initialize>>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.CodeAnalysis.Scripting.ScriptExecutionState.<RunSubmissionsAsync>d__9`1.MoveNext()