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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Richard LeeSoftware 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.


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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.