473,396 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

MyClass2 = MyClass1 -> ByRef????

Hi,

I have 2 instances of a user-defined class. When I do a cls2 = cls1, and I
change a property of cls2, this property is also changed in my cls1!!

Does anybody know what the reason of this is? and how I can prevent it?

Thanks,

Pieter

I'm using VB.NET 2003.
This is my sample code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim cls1 As New clsMyClass
Dim cls2 As clsMyClass
cls2 = Nothing
cls2 = cls1
MessageBox.Show(cls1.Icon Is Nothing)
Dim bmp As New Bitmap(20, 20, Imaging.PixelFormat.Format32bppPArgb)
cls2.Icon = bmp
MessageBox.Show(cls1.Icon Is Nothing)
End Sub

Public Class clsMyClass
Private m_Icon As Bitmap

Public Property Icon() As Bitmap
Get
Return m_Icon
End Get
Set(ByVal Value As Bitmap)
m_Icon = Value
End Set
End Property

End Class
Aug 10 '05 #1
16 1340
Hi,
There are probably many ways to accomplish this, but one way to prevent it
would be to use a copy constructor like this: (That should do the trick)

Public Class clsMyClass
Private m_Icon As Bitmap

Public Sub New()
'Do nothing for now, but you can add your code to it
End Sub

Public Sub New(ByVal ClsToCopy as clsMyClass)
Me.Icon = ClsToCopy.Icon
End Sub

Public Property Icon() As Bitmap
Get
Return m_Icon
End Get
Set(ByVal Value As Bitmap)
m_Icon = Value
End Set
End Property

End Class

"DraguVaso" <pi**********@hotmail.com> a écrit dans le message de
news:uh*************@TK2MSFTNGP10.phx.gbl...
Hi,

I have 2 instances of a user-defined class. When I do a cls2 = cls1, and I
change a property of cls2, this property is also changed in my cls1!!

Does anybody know what the reason of this is? and how I can prevent it?

Thanks,

Pieter

I'm using VB.NET 2003.
This is my sample code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim cls1 As New clsMyClass
Dim cls2 As clsMyClass
cls2 = Nothing
cls2 = cls1
MessageBox.Show(cls1.Icon Is Nothing)
Dim bmp As New Bitmap(20, 20, Imaging.PixelFormat.Format32bppPArgb) cls2.Icon = bmp
MessageBox.Show(cls1.Icon Is Nothing)
End Sub

Public Class clsMyClass
Private m_Icon As Bitmap

Public Property Icon() As Bitmap
Get
Return m_Icon
End Get
Set(ByVal Value As Bitmap)
m_Icon = Value
End Set
End Property

End Class

Aug 10 '05 #2
That's because cls1 and cls2 are *references* to objects and not the
actual objects themselves. Assigning cls2 to cls1 simply makes them
both refer to the same object and that's why changing a property
affects both.

I suggest you implement the ICloneable interface in your user defined
class and do something like
cls2 = (MyClass)cls1.Clone();

Regards
Senthil

Aug 10 '05 #3
DraguVaso wrote:
I have 2 instances of a user-defined class. When I do a cls2 = cls1,
and I change a property of cls2, this property is also changed in my
cls1!!


You don't have two instances, you only have one.

Your instance is created in this line:

\\\
Dim cls1 As New clsMyClass
///

The following line does not create another instance, it simply points cls2
at the existing instance that cls1 is already referencing:

\\\
cls2 = cls1
///

After this, both cls1 and cls2 are pointing to the same object instance,
hence the behaviour you described.

To prevent it, create two object instances:

\\\
Dim cls1 As New clsMyClass
Dim cls2 As New clsMyClass
///

--

(O)enone
Aug 10 '05 #4
Well, I tried that, but I have a Brush-property in my Class, and that gives
me this exception...

The type System.Drawing.Brush in Assembly System.Drawing,
Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a is not
marked as serializable. at
System.Runtime.Serialization.FormatterServices.Int ernalGetSerializableMember
s(RuntimeType type, Boolean excludeNonSerializable)
at
System.Runtime.Serialization.FormatterServices.Get SerializableMembers(Type
type, StreamingContext context)
etc etc etc...

Any idea to get around this problem?

"S. Senthil Kumar" <se**************@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
That's because cls1 and cls2 are *references* to objects and not the
actual objects themselves. Assigning cls2 to cls1 simply makes them
both refer to the same object and that's why changing a property
affects both.

I suggest you implement the ICloneable interface in your user defined
class and do something like
cls2 = (MyClass)cls1.Clone();

Regards
Senthil

Aug 10 '05 #5
>From the exception, it looks like you tried serializing and
deserializing your class to get a copy. System.Drawing.Brush is not
serializable and that's why you are getting the exception.

Do you need to deep copy everything?

Regards
Senthil

Aug 10 '05 #6
Pieter,

Any reason why you don't do what Oenone suggest you?

Cor
Aug 10 '05 #7
Yes unfortunately yes :) It's actually a deep copy that I need to make.
I guess ThunderMusic's method will be the best now...
"S. Senthil Kumar" <se**************@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
From the exception, it looks like you tried serializing and

deserializing your class to get a copy. System.Drawing.Brush is not
serializable and that's why you are getting the exception.

Do you need to deep copy everything?

Regards
Senthil

Aug 11 '05 #8
Because it doesn't work...
Dim cls1 As New clsMyClass
Dim cls2 As New clsMyClass
cls2 = cls1 '-> This still creates a reference to my cls1, so
changes I make to cls2 will be changed automaticly to cls1 also...

"Cor Ligthert [MVP]" <no************@planet.nl> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
Pieter,

Any reason why you don't do what Oenone suggest you?

Cor

Aug 11 '05 #9
I found a solution somewhere that works. It's using Reflection, and I
implemented in a New() just like ThunderMusic suggested. It works great!
Thanks a lot for the suggestions!

Imports System.Reflection

Public Sub New(ByVal clsSource As clsMyClass)
MyBase.New()

Dim pi As PropertyInfo() = GetType(clsMyClass).GetProperties
Dim objValue As Object

For intX As Integer = 0 To pi.Length - 1
With pi(intX)
'If .GetIndexParameters().Length = 0 Then
'Copy
objValue = .GetValue(clsSource, Nothing)
'Paste
.SetValue(Me, objValue, Nothing)
'Else
' Debug.WriteLine(.Name & " " & "<array>")
'End If
End With
Next intX
End Sub


"DraguVaso" <pi**********@hotmail.com> wrote in message
news:uh*************@TK2MSFTNGP10.phx.gbl...
Hi,

I have 2 instances of a user-defined class. When I do a cls2 = cls1, and I
change a property of cls2, this property is also changed in my cls1!!

Does anybody know what the reason of this is? and how I can prevent it?

Thanks,

Pieter

I'm using VB.NET 2003.
This is my sample code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim cls1 As New clsMyClass
Dim cls2 As clsMyClass
cls2 = Nothing
cls2 = cls1
MessageBox.Show(cls1.Icon Is Nothing)
Dim bmp As New Bitmap(20, 20, Imaging.PixelFormat.Format32bppPArgb) cls2.Icon = bmp
MessageBox.Show(cls1.Icon Is Nothing)
End Sub

Public Class clsMyClass
Private m_Icon As Bitmap

Public Property Icon() As Bitmap
Get
Return m_Icon
End Get
Set(ByVal Value As Bitmap)
m_Icon = Value
End Set
End Property

End Class

Aug 11 '05 #10
Pieter,

You are always talking about classes

Dim cls1 as New clsMyClass
Dim cls2 as New clsMyClass
is in fact
Dim obj1 as new clsMyClass
dim obj2 as new clsMyClass

Gives 2 completly independedn objects

dim obj1 = obj2

Sets the reference from obj2 to obj1, so the point to the same object

In the same time the first instanced obj2 has no reference anymore and
therefore that obj2 will be garbaged by the GC.

I hope this gives an idea,

Cor
Aug 11 '05 #11
Oh no, forget about my solution: It's totally worthless. ok, it works, but
it eats resources like hell!! It's slowing down everything, and it's too
much remarkable... :-(
"DraguVaso" <pi**********@hotmail.com> wrote in message
news:OK**************@TK2MSFTNGP12.phx.gbl...
I found a solution somewhere that works. It's using Reflection, and I
implemented in a New() just like ThunderMusic suggested. It works great!
Thanks a lot for the suggestions!

Imports System.Reflection

Public Sub New(ByVal clsSource As clsMyClass)
MyBase.New()

Dim pi As PropertyInfo() = GetType(clsMyClass).GetProperties
Dim objValue As Object

For intX As Integer = 0 To pi.Length - 1
With pi(intX)
'If .GetIndexParameters().Length = 0 Then
'Copy
objValue = .GetValue(clsSource, Nothing)
'Paste
.SetValue(Me, objValue, Nothing)
'Else
' Debug.WriteLine(.Name & " " & "<array>")
'End If
End With
Next intX
End Sub


"DraguVaso" <pi**********@hotmail.com> wrote in message
news:uh*************@TK2MSFTNGP10.phx.gbl...
Hi,

I have 2 instances of a user-defined class. When I do a cls2 = cls1, and I change a property of cls2, this property is also changed in my cls1!!

Does anybody know what the reason of this is? and how I can prevent it?

Thanks,

Pieter

I'm using VB.NET 2003.
This is my sample code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim cls1 As New clsMyClass
Dim cls2 As clsMyClass
cls2 = Nothing
cls2 = cls1
MessageBox.Show(cls1.Icon Is Nothing)
Dim bmp As New Bitmap(20, 20,

Imaging.PixelFormat.Format32bppPArgb)
cls2.Icon = bmp
MessageBox.Show(cls1.Icon Is Nothing)
End Sub

Public Class clsMyClass
Private m_Icon As Bitmap

Public Property Icon() As Bitmap
Get
Return m_Icon
End Get
Set(ByVal Value As Bitmap)
m_Icon = Value
End Set
End Property

End Class


Aug 11 '05 #12
DraguVaso wrote:
Because it doesn't work...
Dim cls1 As New clsMyClass
Dim cls2 As New clsMyClass
cls2 = cls1 '-> This still creates a reference to my cls1,
so changes I make to cls2 will be changed automaticly to cls1 also...


I think I'm struggling to work out what you're actually trying to do.

You asked a question about why after running the above code changes made to
cls2 also affect cls1, and we've answered that question.

What exactly is the problem you are trying to solve? Are you trying to
create two separate objects and copy all of the property values from one
object to the other?

--

(O)enone
Aug 11 '05 #13
Yes indeed! That's exactly what I want!
I want my cls2 to be exactly the same as my cls1, but when I change a value
in cls2, it shouldn't affect cls1. What I need is a Deep Copy...

I now made a Constructor of my clsMyclass that gets a clsMyClass argument,
and copies all it's properties one by one in its own properties. It isn't
really beautiful, but it works... My class has only 10 property's so it's
not too hard, but when having classes with much more properties a nicer
solution should be welcome, hehe :)

Thanks anyway for the explanation and the help.

Pieter

"Oenone" <oe****@nowhere.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
DraguVaso wrote:
Because it doesn't work...
Dim cls1 As New clsMyClass
Dim cls2 As New clsMyClass
cls2 = cls1 '-> This still creates a reference to my cls1,
so changes I make to cls2 will be changed automaticly to cls1 also...
I think I'm struggling to work out what you're actually trying to do.

You asked a question about why after running the above code changes made

to cls2 also affect cls1, and we've answered that question.

What exactly is the problem you are trying to solve? Are you trying to
create two separate objects and copy all of the property values from one
object to the other?

--

(O)enone

Aug 11 '05 #14
Pieter,

If you want a deepcopy of an object than the most simple method to make the
class from which its instanced serializable and than to serialise it and
create using deserialization a copy of that object.

I hope this helps,

Cor
Aug 11 '05 #15
Your solution doesn't seem to do a deep copy either. You get the
property values using reflection and just assign them to the new
object, so reference type member variables will still be shared.

Regards
Senthil

Aug 11 '05 #16
Yes I tried that, but unfortunately I got an error (as I mentioned alreaddy
somewhere in another post): It seems that a Brush-object in't
serializable...
The type System.Drawing.Brush in Assembly System.Drawing,
Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a is not
marked as serializable. at
System.Runtime.Serialization.FormatterServices.Int ernalGetSerializableMember
s(RuntimeType type, Boolean excludeNonSerializable)
at
System.Runtime.Serialization.FormatterServices.Get SerializableMembers(Type
type, StreamingContext context)
etc etc etc...

"Cor Ligthert [MVP]" <no************@planet.nl> wrote in message
news:ef**************@TK2MSFTNGP12.phx.gbl...
Pieter,

If you want a deepcopy of an object than the most simple method to make the class from which its instanced serializable and than to serialise it and
create using deserialization a copy of that object.

I hope this helps,

Cor

Aug 12 '05 #17

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

Similar topics

1
by: Jon Slaughter | last post by:
I have a chain of classes(i.e., a series of classes each containing an array of the next class). Each class has array like access. struct Myclass1 { vector(Myclass2) _Myclass2; Myclass2&...
3
by: news | last post by:
Is this construction possible???? class MyClass1 { .... } class MyClass2 : MyClass1 { ....
3
by: Fei Li | last post by:
Hi, take string class as an example, who can explain the difference? Thanks
0
by: MXL | last post by:
Hello, I have 2 classes: MyClass1 and MyClass2. MyClass1 contains an Array(3 elements) of MyClass2, which contains an array of bytes(3 elements). __gc public class MyClass2 { public:...
7
by: Iain Mcleod | last post by:
Hi This must be an often encountered problem. I want to declare an abstract class or an interface with nothing but several static constants so that I can use polymorphism when I call each of them...
6
by: Stefan Tappertzhofen | last post by:
Hello NG, I've got a problem with function parameters. Here is my first class: class MyClass1 { public: double dFoo(MyClass2* , double); };
4
by: Brian Blais | last post by:
Hello, I am trying to organize some of my code, and am having a little trouble with the import logic. I find I often have something like: MyPackage/ Part1/ # wants to use functions in...
4
by: Deep | last post by:
Can I use a class in this manner, where a constructor is of templated: template<typename T> class my_class{ public: int x_; public: template<typename U> my_class(const my_class<U>& other ) :...
2
by: chris fellows | last post by:
In VS2005 (C#) I want to set the properties of an object dynamically at runtime from an XML configuration file but without having to know the property name when writing the code. The properties are...
12
by: raylopez99 | last post by:
Keywords: scope resolution, passing classes between parent and child forms, parameter constructor method, normal constructor, default constructor, forward reference, sharing classes between forms....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.