Chapter 10.

Alter the self-assessment question from the previous chapter so the Film class uses properties instead of get and set methods. Add validation code to set the rating to 10, if the user enters anything over 10, and set the rating to 0 if the user enters anything less than 0.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

namespace Films2
{

class Class1
{

[Serializable]
public class film
{

private string filmTitle;
private int filmRating;

public string Title
{

get
{

return filmTitle;

}

set
{

filmTitle = value;

}

}

public int Rating
{

get
{

return filmRating;

}

set
{

filmRating = value;

if (value > 10)

filmRating = 10;

if (value < 0)

filmRating = 0;

}

}

}

[STAThread]
static void Main(string[] args)
{

BinaryWriter bw = new BinaryWriter (File.Open("Film.dat", FileMode.Create));
string ans;

do
{

film film1 = new film();
Console.WriteLine("Enter the title of a film: ");
film1.Title= Console.ReadLine();

Console.WriteLine("Enter the rating for the film: ");
film1.Rating= int.Parse(Console.ReadLine());
 

BinaryFormatter fm = new BinaryFormatter();
fm.Serialize(bw.BaseStream, film1);
Console.Write("Enter another film? (Y/N): ");
ans = Console.ReadLine();

}while (ans != "N");

bw.Close();

BinaryReader br = new BinaryReader(File.Open("Film.dat", FileMode.Open));
film film2 = new film();
BinaryFormatter bm = new BinaryFormatter();

while (br.PeekChar() != -1)
{

film2 = (film)bm.Deserialize(br.BaseStream);
Console.WriteLine(film2.Title);
Console.WriteLine(film2.Rating);

}

br.Close();

}

}

}