-1

here is what im trying to do,

someClass object = new someClass();
Type a=object.GetType();
a someOtherObject =new a();

but the variable a can't be used in place of someClass even though i saved it as a type. I was wondering if there is an alternative method of doing something like this.

As for the why, i want to make a method that takes in a list of monster in my game and it picks a random one, creates a new object out of the one it has chosen and adds it to a seperate list.

1 Answers1

0

You can use Activator.CreateInstance for the purpose

var obj = new someClass();
Type type = obj.GetType();
var someOtherObject = Activator.CreateInstance(type);
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • whats the difference between using var and someClass? – Chicken Master Nov 23 '19 at 18:34
  • var is an implicitly typed local variable, which is equivalent to a strongly typed variable, the only difference is that the compiler automatically determines the type. So with regard to context of your question, using both var and someClass is equivalent. The Compiler recognizes that obj is of type someClass – Anu Viswan Nov 23 '19 at 18:54
  • You could read more on var here https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var – Anu Viswan Nov 23 '19 at 18:54