Question

In: Computer Science

C# Create a console application named that creates a list of shapes, uses serialization to save...

C#

Create a console application named that creates a list of shapes, uses serialization to save it to the filesystem using XML, and then deserializes it back:

// create a list of Shapes to serialize
var listOfShapes = new List<Shape>
{
new Circle { Colour = "Red", Radius = 2.5 },
new Rectangle { Colour = "Blue", Height = 20.0, Width = 10.0 },
new Circle { Colour = "Green", Radius = 8 },
new Circle { Colour = "Purple", Radius = 12.3 },
new Rectangle { Colour = "Blue", Height = 45.0, Width = 18.0 }
};

Shapes should have a read-only property named Area so that when you deserialize, you can output a list of shapes, including their areas, as shown here:

List<Shape> loadedShapesXml = serializerXml.Deserialize(fileXml)
as List<Shape>;
foreach (Shape item in loadedShapesXml) {
WriteLine($"{item.GetType().Name} is {item.Colour} and has an
area of {item.Area}");
}

This is what your output should look like when you run the application:

Loading shapes from XML:
Circle is Red and has an area of 19.6349540849362
Rectangle is Blue and has an area of 200
Circle is Green and has an area of 201.061929829747
Circle is Purple and has an area of 475.2915525616
Rectangle is Blue and has an area of 810

Solutions

Expert Solution

Short Summary:

  • First, Implement Shape abstract class. Then extend it to Rectangle and Circle.
  • Use serialize attribute as required

Source Code:

Shape.cs File:

using System;

using System.Xml.Serialization;

namespace SerializeDemo

{

    [XmlInclude(typeof(Circle))]

    [XmlInclude(typeof(Rectangle))]

    [Serializable]

    public abstract class Shape

    {

        public string Colour { get; set; }

        public abstract double Area { get; }

    }

}

***************************************************

Circle.cs File:

using System;

namespace SerializeDemo

{

    [Serializable]

    public class Circle:Shape

    {

        public double Radius { get; set; }

        // circle Area = pi * radius^2

        public override double Area { get { return 3.14 * Radius * Radius; } }

    }

}

***************************************************

Rectangle.cs File:

using System;

namespace SerializeDemo

{

    [Serializable]

    public class Rectangle:Shape

    {

        public double Height { get; set; }

        public double Width { get; set; }

        // Rectangle Area = Height * Width

        public override double Area { get { return Height * Width; } }

    }

}

***************************************************

DemoProgram

using System;

using System.Collections.Generic;

using System.Xml.Serialization;

using System.IO;

namespace SerializeDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            string filePath = "Shapes.xml";

           

            // create a list of Shapes to serialize

            var listOfShapes = new List<Shape>

                {

                new Circle { Colour = "Red", Radius = 2.5 },

                new Rectangle { Colour = "Blue", Height = 20.0, Width = 10.0 },

                new Circle { Colour = "Green", Radius = 8 },

                new Circle { Colour = "Purple", Radius = 12.3 },

                new Rectangle { Colour = "Blue", Height = 45.0, Width = 18.0 }

                };

         

            // Serialize the object

            XmlSerializer serializerXml = new XmlSerializer(typeof(List<Shape>));

            System.IO.FileStream fileXmlSerialize = System.IO.File.Create(filePath);

            serializerXml.Serialize(fileXmlSerialize, listOfShapes);

            fileXmlSerialize.Close();

            //Deserialize the object

            using (StreamReader fileXml = new StreamReader(filePath))

            {

                List<Shape> loadedShapesXml = serializerXml.Deserialize(fileXml) as List<Shape>;

                foreach (Shape item in loadedShapesXml)

                {

                    Console.WriteLine($"{item.GetType().Name} is {item.Colour} and has an area of { item.Area}");

                }

            }

            Console.ReadLine();

        }

    }

}

Sample Run:

**************************************************************************************

Feel free to rate the answer and comment your questions, if you have any.

Please upvote the answer and appreciate our time.

Happy Studying!!!

**************************************************************************************


Related Solutions

C# Create a console application that prompts the user to enter a regular expression, and then...
C# Create a console application that prompts the user to enter a regular expression, and then prompts the user to enter some input and compare the two for a match until the user presses Esc: The default regular expression checks for at least one digit. Enter a regular expression (or press ENTER to use the default): ^[a- z]+$ Enter some input: apples apples matches ^[a-z]+$? True Press ESC to end or any key to try again. Enter a regular expression...
Language: C# Create a new Console Application. Your Application should ask the user to enter their...
Language: C# Create a new Console Application. Your Application should ask the user to enter their name and their salary. Your application should calculate how much they have to pay in taxes each year and output each amount as well as their net salary (the amount they bring home after taxes are paid!). The only taxes that we will consider for this Application are Federal and FICA. Your Application needs to validate all numeric input that is entered to make...
C# & ASP.NET Create a console application that prompts the user to enter a regular expression,...
C# & ASP.NET Create a console application that prompts the user to enter a regular expression, and then prompts the user to enter some input and compare the two for a match until the user presses Esc: The default regular expression checks for at least one digit. Enter a regular expression (or press ENTER to use the default): ^[a- z]+$ Enter some input: apples apples matches ^[a-z]+$? True Press ESC to end or any key to try again. Enter a...
C++ Write a program that creates two rectangular shapes and then animates them. The two shapes...
C++ Write a program that creates two rectangular shapes and then animates them. The two shapes should start on opposite ends of the screen and then move toward each other. When they meet in the middle of the screen, each shape reverses course and moves toward the edge of the screen. The two shapes keep oscillating and bouncing off of each other in the middle of the screen. The program terminates when the shapes meet each other in the middle...
:  Create a new blank C# console application Your basal metabolic rate is the rate...
:  Create a new blank C# console application Your basal metabolic rate is the rate at which the body uses energy while at rest to keep vital functions going, such as breathing and keeping warm. This calculation is vital to weight management, as it allows you to determine calories needed to maintain, lose, or gain weight. To determine your BMR, use the appropriate formula: Female: 655+(4.35 x weight in pounds)+(4.7 x height in inches)-(4.7 x age in years) Males:...
Create a C# Windows Console application that displays the following patterns separately, one after the other....
Create a C# Windows Console application that displays the following patterns separately, one after the other. You MUST use nested for loops to generate the patterns. All asterisks (*) should be displayed by a single statement of the form Console.Write("*"); which causes the asterisks to display side by side. A statement of the form Console.WriteLine(); can be used to move to the next line. A statement of the form Console.Write(" "); can be used to display a space for the...
JAVA PROJECT Step 1: Create an application named YourInitials_Project 3 that uses a class to convert...
JAVA PROJECT Step 1: Create an application named YourInitials_Project 3 that uses a class to convert number grades to letter grades and another class for data validation. Make comments including your name, date, and project name as well as appropriate comments throughout your application that include the step number. Step 2: Create code to print Titles Step 3: Create a variable to hold user’s choice. Remember that all variables must begin with your initials and should be descriptive. Step 4:...
(Not in Swing) Write a JavaFX application that creates polyline shapes dynamically using mouse clicks. Each...
(Not in Swing) Write a JavaFX application that creates polyline shapes dynamically using mouse clicks. Each mouse click adds a new line segment to the current polyline from the previous point to the current mouse position. Allow the user to end the current polyline with the double click. Also, provide a button that clears the window and allows the user to begin again.
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a package named threeDimensional and put all 3 of the classes discussed below in this package Include a header comment to EACH OF your files, as indicated in your instructions. Here's a link describing the header. Note that headers are not meant to be in Javadoc format. Note that Javadoc is a huge part of your grade for this assignment. Javadoc requires that every class,...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a package named threeDimensional and put all 3 of the classes discussed below in this package Include a header comment to EACH OF your files, as indicated in your instructions. Here's a link describing the header. Note that headers are not meant to be in Javadoc format. Note that Javadoc is a huge part of your grade for this assignment. Javadoc requires that every class,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT