I have an array X of 10 elements. I would like to create a new array containing all the elements from X that begin at index 3 and ends in index 7. Sure I can easily write a loop that will do it for me but I would like to keep my code as clean as possible. Is there a method in C# that can do it for me?
Something like (pseudo code):
Array NewArray = oldArray.createNewArrayFromRange(int BeginIndex , int EndIndex)
Array.Copy doesn’t fit my needs. I need the items in the new array to be clones. Array.copy is just a C-Style memcpy equivalent, it’s not what I’m looking for.
You could add it as an extension method:
Update re cloning (which wasn’t obvious in the original question). If you really want a deep clone; something like:
This does require the objects to be serializable (
[Serializable]orISerializable), though. You could easily substitute for any other serializer as appropriate –XmlSerializer,DataContractSerializer, protobuf-net, etc.Note that deep clone is tricky without serialization; in particular,
ICloneableis hard to trust in most cases.