Search code examples
c#office-interop

Copy Object Value of PPT shapes in C#


Is it possible to create a List of PPT Shapes and have them maintain their values even after deleting the original from the slide?

I want to create a list of all shapes in a slide, manipulate the slide, but still maintain all info from the original.

List<Microsoft.Office.Interop.PowerPoint.Shape> pptShapes = new List<Microsoft.Office.Interop.PowerPoint.Shape>();
for (int jCurr = 1; jCurr <= slide.Shapes.Count; jCurr++)
                {                        
                    currShp = slide.Shapes[jCurr];
                    pptShapes.Add(currShp);
                }
//Do something else like delete a few of the shapes
if (slide.Shapes[1] != null)
{
     slide.Shapes[1].Delete();
}

//Below gives me Null since I deleted the original shape
MessageBox.Show(pptShapes[0].Type.ToString());

I want to maintain the original shapes because later I plan to copy/paste special into placeholders, etc. so I need more than just the content.


Solution

  • If you want to reference a value that you would want to remove from some kind of collection, doesn't matter if COM or Managed, you would need to perform a copy by value. In your example this would look like this:

    List<Microsoft.Office.Interop.PowerPoint.Shape> pptShapes = new List<Microsoft.Office.Interop.PowerPoint.Shape>();
    for (int jCurr = 1; jCurr <= slide.Shapes.Count; jCurr++)
                    {                        
                        currShp = slide.Shapes[jCurr];
                        pptShapes.Add(currShp);
                    }
    
    string deletedString = "";
    
    if (slide.Shapes[1] != null)
    {
         string deletedString = pptShapes[0].Type.ToString();
         slide.Shapes[1].Delete();
    }
    
    MessageBox.Show(deletedString);
    

    For reference types you would need to perform DeepCopy of this object.