0

I'm not quite sure how to word my question (which may be why I can't effectively search for an answer). I have a method:

public void spawnDisaster(new disaster) 
{
    //code for starting a new disaster
}

It uses a custom class called disaster, which I have extended like this:

public class di_flood : disaster 
{
    desc = "Oh no, a flood!";
}

public class di_tsunami : disaster 
{
    desc = "It's a tsunami, run!";
}

I want a disaster to be able to create a copy of itself. Like this:

public class disaster 
{
   public void makeANewOneOfThese() 
   {
      spawnDisaster(new this.getType() );
   }
}

But, of course, this doesn't work: getType() returns a Type, rather than the actual class, so I can't make a new instance from it.

I've been googling around for the last 2 hours trying to get this to work, and I know it has something to do with Reflection and might involve Generics, but now I'm just confused. It feels like there's probably a simple(ish) way to do this but I just can't figure it out.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 2
    look for `Activator.CreateInstance` method – Ehsan Sajjad Apr 20 '18 at 13:53
  • "I've been googling around for the last 2 hours trying to get this to work" Did you search for "create instance from existing instance c#"? Would be my first try – MakePeaceGreatAgain Apr 20 '18 at 14:00
  • I guess you are trying to clone an Instance. Take a look at this answer. https://stackoverflow.com/questions/2106725/how-do-i-copy-an-instance-of-an-object – Sumanth Apr 20 '18 at 14:04
  • Since everyone seemed to be very against cloning, I just added this method to the disaster class: public virtual void makeANewOneOfThese() { } Then each disaster class got this as well public override void makeANewOneOfThese() { spawnDisaster(new [the type that contains this method]); } – Jamie Patton Apr 23 '18 at 12:18

0 Answers0