473,657 Members | 2,521 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy of class instance

I'm sorry to ask such a fundamental question, but is it possible to create a
copy of an object in VB.Net 2005?

I have an app which, on load, creates an instance of a class, into which it
reads a load of data from XML. What I want is to be able to declare a new
instance of this class and make it a copy of the existing instance. This
way I can spawn various instances with their own updated properties

The code "Dim NewInst as MyClass = OldInst" creates a reference to the
existing instance and, therefore, changing any properties of NewInst are
reflected in OldInst.

Is there a simple way to do what I need?

Many thanks for any help.
Jul 27 '06 #1
3 6239
Chris Pratt wrote:
I'm sorry to ask such a fundamental question, but is it possible to create a
copy of an object in VB.Net 2005?

I have an app which, on load, creates an instance of a class, into which it
reads a load of data from XML. What I want is to be able to declare a new
instance of this class and make it a copy of the existing instance. This
way I can spawn various instances with their own updated properties

The code "Dim NewInst as MyClass = OldInst" creates a reference to the
existing instance and, therefore, changing any properties of NewInst are
reflected in OldInst.

Is there a simple way to do what I need?

Many thanks for any help.

I don't know of a way to automatically do this, but you really need to
make a clone method and then inside the clone method set all the
properties to what they are in the current instance.

You may be able to do this with reflection in just a couple lines of
code. This sample code will do all the public properties.

Dim NewInstance As New IPEGCompany
Dim myType As Type = GetType(IPEGCom pany)
Dim myProperties() As Reflection.Prop ertyInfo =
myType.GetPrope rties((Reflecti on.BindingFlags .Public Or
Reflection.Bind ingFlags.Instan ce))
' Loop thru the public properties
Dim PropertyItem As Reflection.Prop ertyInfo
For Each PropertyItem In myProperties
PropertyItem.Se tValue(NewInsta nce,
Reader.GetValue (Reader.GetOrdi nal(PropertyIte m.Name)), Nothing)
Next
Jul 27 '06 #2
I'm sorry to ask such a fundamental question, but is it possible to
create a copy of an object in VB.Net 2005?

I have an app which, on load, creates an instance of a class, into
which it reads a load of data from XML. What I want is to be able to
declare a new instance of this class and make it a copy of the
existing instance. This way I can spawn various instances with their
own updated properties

The code "Dim NewInst as MyClass = OldInst" creates a reference to the
existing instance and, therefore, changing any properties of NewInst
are reflected in OldInst.

Is there a simple way to do what I need?
You need to have your object implement IClonable and use the .Clone method
to get a copy of your object. You will be responsible for doing the cloan,
either with a serialize dehydrate/hydrate mechanism or manual property setting.
Jim Wooley
http://devauthority.com/blogs/jwooley/default.aspx
Jul 27 '06 #3
Thanks Chris, that was really helpful. It allowed me to write a generic
function which I can use for all cases, as below:
Public Sub CopyObject(ByVa l ObjectType As Type, _
ByVal ExistingInstanc e As Object, _
ByRef NewInstance As Object)

Dim Props() As Reflection.Prop ertyInfo = _
ObjectType.GetP roperties(Refle ction.BindingFl ags.Public Or _
Reflection.Bind ingFlags.Instan ce)

For Each PropItem As Reflection.Prop ertyInfo In Props

If PropItem.CanWri te Then
PropItem.SetVal ue(NewInstance, _
PropItem.GetVal ue(ExistingInst ance, Nothing), Nothing)
End If

Next

End Sub

Incidentally, what does the Reader object refer to in your example? Is this
a better way of extracting the property values than the way I have done it?

"Chris" <no@spam.comwro te in message
news:ub******** ******@TK2MSFTN GP04.phx.gbl...
Chris Pratt wrote:
>I'm sorry to ask such a fundamental question, but is it possible to
create a copy of an object in VB.Net 2005?

I have an app which, on load, creates an instance of a class, into which
it reads a load of data from XML. What I want is to be able to declare a
new instance of this class and make it a copy of the existing instance.
This way I can spawn various instances with their own updated properties

The code "Dim NewInst as MyClass = OldInst" creates a reference to the
existing instance and, therefore, changing any properties of NewInst are
reflected in OldInst.

Is there a simple way to do what I need?

Many thanks for any help.

I don't know of a way to automatically do this, but you really need to
make a clone method and then inside the clone method set all the
properties to what they are in the current instance.

You may be able to do this with reflection in just a couple lines of code.
This sample code will do all the public properties.

Dim NewInstance As New IPEGCompany
Dim myType As Type = GetType(IPEGCom pany)
Dim myProperties() As Reflection.Prop ertyInfo =
myType.GetPrope rties((Reflecti on.BindingFlags .Public Or
Reflection.Bind ingFlags.Instan ce))
' Loop thru the public properties
Dim PropertyItem As Reflection.Prop ertyInfo
For Each PropertyItem In myProperties
PropertyItem.Se tValue(NewInsta nce,
Reader.GetValue (Reader.GetOrdi nal(PropertyIte m.Name)), Nothing)
Next

Jul 28 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

42
5757
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
5
459
by: I wish | last post by:
I wrote some program #include <iostream> class A { public: A() {} A( const A& t ) { std::cout << "Good" << std::endl; } }; A f()
14
1977
by: MSR | last post by:
I have a couple of questions. 1. Copy Constructor. class A { private: int a1; double d1; char *ptr;
5
8393
by: lion | last post by:
in .net, if you set annstance-A of a class equal to another instance-B, a pointer will add to B, but if i want to create a copy of B instead of pointer, how to operate? Note:serialization isn't permitted 3x
4
1373
by: JonZ | last post by:
I want to declare a local copy of an object so I can modify the local version without affecting the original copy. But when I update my local copy, the original object changes, too. My original object is a collection I’ve defined. I started with a class definition: Public Class MyClassDef Inherits System.Collections.CollectionBase
8
9628
by: downwitch | last post by:
Either I don't understand (entirely possible), or there's no way to copy parts of a class hierarchy from one instance to another. Say I have a class called Foo, and it contains, among other things, a custom collection called SubFoos. If I do something like Dim MyFoo1 As Foo Dim MyFoo2 As Foo 'call something to populate MyFoo1 and its SubFoos...
12
1556
by: tony obrien | last post by:
Hi, I have written a Class Library in VB.net which provides Props/Meths to a caller to hide the uglinesses of a TCP message protocol between a Client and a Server. All this works just fine. Now I am trying to develop a LOAD TESTER app which spawns lotso' threads each with this capability to bang the server.
7
2157
by: pallav | last post by:
I'm having some trouble with my copy constructor. I've tried using gdb to find the bug, but it seg faults in the destructor. I'm not able to see what I'm doing wrong. Since I'm using pointers, I need deep copy and I believe I'm doing that in my constructors. Can someone help me see what I'm missing out? Here is my code. typedef boost::shared_ptr<FactorFactorPtr; enum FactorTypeT
11
2278
by: Dijkstra | last post by:
Hi folks! First, this is the code I'm using to expose the problem: ------------------------------------------------------------------ #include <functional> #include <string> #include <iostream> using namespace std;
3
1574
by: yoma | last post by:
python version 2.5 in module copy we all know that copy have two method: copy() and deepcopy(). and the explain is - A shallow copy constructs a new compound object and then (to the extent possible) inserts *the same objects* into it that the original contains. - A deep copy constructs a new compound object and then, recursively, inserts *copies* into it of the objects found in the original.
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8823
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8726
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1604
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.