0

In C# how are new object instances created that are copies of existing ones instead of default ones.

For example:

door a = new door();
door b = a;
door c = new door(a);
b.open();
a.is_open(); // yes
b.is_open(); // yes
c.is_open(); // no

edit: In case it's usefull, I made this after accepting the answer and will post it here.

public class copyable // inherit from this to make you'r object copyable
{
    public heading copy()
    {
        return (heading)MemberwiseClone();
    }
}
alan2here
  • 3,223
  • 6
  • 37
  • 62
  • 1
    this all depends on what `door` is - is it a reference or value type? What does the constructor do that accepts another `door` ? – BrokenGlass Oct 16 '11 at 18:39
  • This might help: http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp – goto10 Oct 16 '11 at 18:40

2 Answers2

3

When passing a parameter in a constructor there is no easy way to create a copy besides copying all the fields. You could use door c = a.MemberwiseClone(); to create a shallow copy, or roll your own.

Bas
  • 26,772
  • 8
  • 53
  • 86
  • I see MemberwiseClone is protected, this means everything that needs to be copyable needs a copy member function that uses MemberwiseClone. – alan2here Oct 16 '11 at 19:03
0

If you want to create a coppy of a object, you have to create a copy constructor or inherent them off iclonable

Frederiek
  • 1,605
  • 2
  • 17
  • 32
  • 4
    Gotta disappoint you, but ICloneable is [considered obsolete/bad practice](http://blogs.msdn.com/b/brada/archive/2004/05/03/125427.aspx) – Claus Jørgensen Oct 16 '11 at 18:50
  • Well my first answer wass the copy constructor. That is what i always use – Frederiek Oct 16 '11 at 19:18
  • +1 @ClausJørgensen but I think it's funny that the article is titled "Should we Obsolete ICloneable" and it's from 2004 and now we are in 2011 :-) – xanatos Oct 16 '11 at 19:55