Practice and explore

Test your knowledge and understanding by answering some questions, get some hands-on practice, and explore this chapter's topics with deeper research.

Exercise 10.1 - test your knowledge

Answer the following questions:

  1. What is the difference between using the File class and the FileInfo class?
  2. What is the difference between the ReadByte method and the Read method of a stream?
  3. When would you use the StringReader, TextReader, and StreamReader classes?
  4. What does the DeflateStream type do?
  5. How many bytes per character does the UTF-8 encoding use?
  6. What is an object graph?
  7. What is the best serialization format to choose for minimizing space requirements?
  8. What is the best serialization format to choose for cross-platform compatibility?

Exercise 10.2 - practice serializing as XML

Create a console application named Ch10_Exercise02 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

Exercise 10.3 - explore serialization formats

Create a console application named Ch10_Exercise03 that queries the Northwind database for all the categories and products and then serializes the data using at least three formats of serialization available to .NET Core.

Which uses the least number of bytes?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.206.69