2

I have a dictionary such that: Dictionary<string, SomeClass> template

Basically, what I want to do is get a copy of the object contained in template. However, I can't seem to create a method that will retrieve the object by value. I am aware of ref and out, but these are the exact opposite of what I want. A struct would be perfect, but unfortunately, SomeClass must inherit from another class and/or an interface.

Is there some way to do what I want? This seems like it should be really simple.

Kyle Baran
  • 1,793
  • 2
  • 15
  • 30
  • 2
    You can copy the object yourself, and pass the reference to the copy back: http://stackoverflow.com/questions/139592/what-is-the-best-way-to-clone-deep-copy-a-net-generic-dictionarystring-t – Joshua Enfield Dec 23 '12 at 06:10
  • 1
    Agree with comment above. C# returns object types by ref. If you want a copy to manipulate, its on you to create a copy. – Glenn Ferrie Dec 23 '12 at 06:11
  • So basically, I just have to manually invoke `new SomeClass()` and manually populate all the data from another instance of SomeClass? – Kyle Baran Dec 23 '12 at 06:21
  • 1
    [Ignoring details of autocopying methods] In one form or another, yes. You might consider returning a new copy of SomeClass for any method that mutates state and not allow any setters on properties. Then you effectively have an immutable SomeClass, but the fact remains you will still need to copy SomeClass in one form or another yourself. – Joshua Enfield Dec 23 '12 at 07:01

1 Answers1

6

You would need a copy constructor

You can also implement ICloneable interface or create your own interface

this would also help you!

Community
  • 1
  • 1
Anirudha
  • 32,393
  • 7
  • 68
  • 89