Solution: Serializing as XML
Explore how to serialize a list of shape objects to XML and deserialize them back in C#. Understand implementing abstract properties like area in derived classes Circle and Rectangle, and managing file-based data storage using XML serialization.
We'll cover the following...
Problem statement
Creates a list of shapes, uses serialization to save it to the filesystem using XML, and then deserializes it back:
Shapes should have a read-only property named Area so that when deserialized, it can output a list of shapes, including their areas, as shown here:
Step-by-step solution
Let’s look at our solution by comprehensively understanding it.
Let’s have a look at Program.cs file:
In this file, we are initializing a List<Shape> named listOfShapes. The list is populated with instances of Circle and Rectangle objects, representing shapes. These shapes are specified with various properties, such as color, radius, height, and width. Then, we created objects that know how to serialize and deserialize a list of shape objects. After that, we check if the shapes were successfully loaded from the XML file. If they were loaded, it prints information about each shape, including its type, color, and area. If no shapes were loaded, it prints a message indicating that loadedShapesXml ...