Logarr
Logarr

Reputation: 2417

Duplicating an object in List<T>

Time for my first question! I want to make it known that I'm quite amateur with programming, and I probably don't fully understand the terms I'm about to use.

I'm making a program that takes the results from an Oracle Query and displays them in a DataGridView for manipulation. The data will be used with an imposition software and I need to be able to "split" and "join" rows to make duplicates.

The data comes in from my service layer as a generic collection called CheckOrderLine that contains 20+ objects containing all the data pulled.

I'm looking for a way to take the current CheckOrderLine from my Binding Source, _bs, and make a new CheckOrderLine with all of the same values. I believe this is known as a deep copy.

I've learned that I can use the following code to achieve my goal, but I'm sure there's a better way to do it:

    CheckOrderLine current = (CheckOrderLine)_bs.Current;
    CheckOrderLine cloned = new CheckOrderLine();

    cloned.OrderNumber = current.OrderNumber;
    cloned.Qty = current.Qty;

and so on.

So I guess my question is this: Is there a way to iterate through the CheckOrderLine and set the values for each property in my new object? Also, is there something horribly wrong with the direction I'm headed? I've seen things around the Web talking about using ICloneable in my CheckOrderLine class, but that's way over my head at this point.

EDIT: Had the wrong VS tag. And I fixed some vocabulary.

Upvotes: 1

Views: 53

Answers (1)

Chris Shain
Chris Shain

Reputation: 51349

Congrats on your first project. You are on the right track- from a pure "does it work" perspective, there is nothing wrong with the way that you are doing it now- just copy one property after another.

Professional developers usually (hopefully) try to strive to develop code in an 'elegant' way. Elegance, in this case, probably means including the logic for cloning a CheckOrderLine inside of the CheckOrderLine class (as a method). This way, if you find another place in your application where you need to clone these things, you can call the same function, and any bug fixes to that function will improve both places where you copy the class. You don't need to implement the ICloneable interface to do that- it's mostly just a convention.

You can also use a technique called Reflection to programmatically iterate over the properties and copy them to a new object, but that's probably over your head right now.

Upvotes: 2

Related Questions