0

I am creating a Stack<T> where I have the type of the Stack in a variable. After I have created the Stack<T>, I am wanting to push items to the Stack. How can I access the Push method?

Here is my code:

var itemType = GetIEnumerableItemType(type);
var stackType = typeof(Stack<>);
var constructedStackType = stackType.MakeGenericType(itemType);
var instance = Activator.CreateInstance(constructedStackType);

EDIT

Here is some code that I have tried that works with a List<T>:

var itemType = GetIEnumerableItemType(type);
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(itemType);
var instance = (IList)Activator.CreateInstance(constructedListType);
//instance.Add("example item");

Thank you

Simon
  • 351
  • 3
  • 8
  • 16
  • If you want to "push" the items from the enumerable you're seemingly using, why not just pass it to the `Stack(IEnumerable collection)` constructor? Otherwise, what use is the `Stack` if you can't access it? – ProgrammingLlama May 19 '21 at 06:08
  • You gotta have tried something that didn't work, right? What did you try and how did it not work? – Sweeper May 19 '21 at 06:12
  • I have added some code that I have got working with some similar code. I am just in need of some help with a different data type. – Simon May 19 '21 at 06:35
  • Generics are a *compile-time* tool, designed to help you catch type errors at compile time. Since you use reflection, the compiler cannot check your types and the advantages of using generics are moot. In that case, a simple `Stack` might be the better and more readable solution. – Heinzi May 19 '21 at 06:41

0 Answers0