How to clone an object ?

G

Guest

Hello, friends,

In c#.net, I need to clone an object passed into a method,

private object generateCollection(object userInfo)
{
//I then need to generate a group of userInfo,
//How can I clone this passed in object?
//Do we have syntax something like this?
//object newUserInfo = new typeof(userInfo);
}

Thanks a lot.
 
C

Chris Mullins [MVP]

Does the object in question support the IClonable interface?

If so, you can just call Clone().

If the interface isn't supported, you best bet is to go ahead (assuming it's
your code) and implement the interface. Other mechanisms such as trying to
Serialize and then Deserialize, will usually end up with some funky results.
 
M

Moty Michaely

Hello, friends,

In c#.net, I need to clone an object passed into a method,

private object generateCollection(object userInfo)
{
//I then need to generate a group of userInfo,
//How can I clone this passed in object?
//Do we have syntax something like this?
//object newUserInfo = new typeof(userInfo);

}

Thanks a lot.

Dear Andrew,

Are you asking if you can create an instance of typeof(userinfo) or
how you can clone the data?

There is no internal way to clone the userInfo object if it's not
implementing a way for doing it.
There are non trivial ways using memory manipulations but I wouldn't
suggest using those.

If you are asking if you could create an instance of it, you can use
the System.Runtime name space to achieve this, or using the
System.Activator class:
http://msdn2.microsoft.com/en-us/library/system.activator.aspx

Again, I wouldn't suggest implementing it this way (by getting object
variables) since instantiating a class requires to be familiar with
the constructors of the class. The way the method is implemented can
cause many runtime exceptions since you can't predict the type of the
class.

It'd be best if you'd clarify your needs.

Moty.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top