How to assign one class object to another? C#

I am working with some C# classes. For example I have one named ProductTypes.
I have an object/instance of this class named myProductTypes. What I need to do is to create a new object instance of the class and assign it to the first instance. Like this:
ProductTypes ohBeJoyfullProductTypes

ohBeJoyfullProductTypes = myProductTypes.

So my question is did I just do that correctly? Also do I need to instantiate the object before I assign it to the first object? Like this:"

ProductTypes ohBeJoyfullProductTypes = new ProductTypes();
ohBeJoyfullProductTypes = myProductTypes.

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

Roshan DavisConnect With a Mentor Commented:
you don't need to instantiate if ohBeJoyfullProductTypes is a reference to your actual object myProductTypes.
ProductTypes ohBeJoyfullProductTypes;
ohBeJoyfullProductTypes = myProductTypes;

Open in new window

Richard LeeConnect With a Mentor Software EnthusiastCommented:
Yes you did it correctly.

On creating the first object it occupies a space in memory therefore assigned a memory address. When assigning the first object to the second they both now point to the same memory address therefore they are both accessing the same data. Change one and you change the other. This applies to reference types whereas value types have a different behaviour.


Mike_MozhaevConnect With a Mentor Commented:
Keep in mind that if you are assigning a reference (as is in your example) then both references point to one object. I.e. if you change object using one reference then you'll get object pointed to by second reference change as well.

If you want to make an independent copy of object then you can implement ICloneable interface in your class and then call Clone(). And copying logic you can implement as you like. For example there's no need to clone values of value type since they always copy by value and string values since they are immutable and hence behave like value types.
All Courses

From novice to tech pro — start learning today.