Visual C#

Serialization

This is an example of the techniques used in file processing to save individual data of primitive types:

13 min read2,764 words12 code samples
Object Serialization and De-Serialization Introduction Consider the following program:
Object Serialization and De-Serialization
Introduction
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
C#
namespace Cars1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            var Make  = txtMake.Text;
            var Model = txtModel.Text;
            var Year  = uint.Parse(txtYear.Text);
            var Color = cbxColors.SelectedIndex;

            var stmCar = new FileStream("Car1.car", FileMode.Create);
            var bnwCar = new BinaryWriter(stmCar);

            try
            {
                bnwCar.Write(Make);
                bnwCar.Write(Model);
                bnwCar.Write(Year);
                bnwCar.Write(Color);
            }
            finally
            {
                bnwCar.Close();
                stmCar.Close();
            }
        }
    }
}

The following is a demonstration of the program in execution:

This is an example of the techniques used in file processing to save individual data of primitive types: while keeping the original behavior intact.

The values can be retrieved with the following code:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Cars1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            var Make  = txtMake.Text;
            var Model = txtModel.Text;
            var Year  = uint.Parse(txtYear.Text);
            var Color = cbxColors.SelectedIndex;

            var stmCar = new FileStream("Car1.car", FileMode.Create);
            var bnwCar = new BinaryWriter(stmCar);

            try
            {
                bnwCar.Write(Make);
                bnwCar.Write(Model);
                bnwCar.Write(Year);
                bnwCar.Write(Color);
            }
            finally
            {
                bnwCar.Close();
                stmCar.Close();
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            var stmCar = new FileStream("Car1.car", FileMode.Open);
            var bnrCar = new BinaryReader(stmCar);

            try
            {
                txtMake.Text = bnrCar.ReadString();
                txtModel.Text = bnrCar.ReadString();
                txtYear.Text = bnrCar.ReadUInt32().ToString();
                cbxColors.SelectedIndex = bnrCar.ReadInt32();
            }
            finally
            {
                bnrCar.Close();
                stmCar.Close();
            }
        }
    }
}

In the same way, you can save the individual fields of a class or you can retrieve the individual fields of a car:

Here is an example: Class: Car.cs

C#
using System;

namespace Cars1
{
    public class Car
    {
        public string Make;
        public string Model;
        public uint Year;
        public int Color;
    }
}
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Cars1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            var vehicle = new Car();
            vehicle.Make  = txtMake.Text;
            vehicle.Model = txtModel.Text;
            vehicle.Year  = uint.Parse(txtYear.Text);
            vehicle.Color = cbxColors.SelectedIndex;

            var stmCar = new FileStream("Car2.car", FileMode.Create);
            var bnwCar = new BinaryWriter(stmCar);

            try
            {
                bnwCar.Write(vehicle.Make);
                bnwCar.Write(vehicle.Model);
                bnwCar.Write(vehicle.Year);
                bnwCar.Write(vehicle.Color);
            }
            finally
            {
                bnwCar.Close();
                stmCar.Close();
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            var stmCar = new FileStream("Car2.car", FileMode.Open);
            var bnrCar = new BinaryReader(stmCar);

            try
            {
                var vehicle = new Car();
                vehicle.Make = bnrCar.ReadString();
                vehicle.Model = bnrCar.ReadString();
                vehicle.Year = bnrCar.ReadUInt32();
                vehicle.Color = bnrCar.ReadInt32();

                txtMake.Text = vehicle.Make;
                txtModel.Text = vehicle.Model;
                txtYear.Text = vehicle.Year.ToString();
                cbxColors.SelectedIndex = vehicle.Color;
            }
            finally
            {
                bnrCar.Close();
                stmCar.Close();
            }
        }
    }
}

When it comes to a class, the problem with saving individual fields is that you could forget to save one of the fields. For example, considering a Car class, if you don't save the Make information of a Car object and retrieve or open the saved object on another computer, the receiving user would miss some information and the car cannot be completely identifiable. An alternative is to save the whole Car object. Object serialization consists of saving a whole object as one instead of its individual fields:

In other words, a variable declared from a class can be saved to a stream and then the saved object can be retrieved later or on another computer. The .NET Framework supports two types of object serialization: binary and SOAP. Practical Learning: Introducing Serialization

  1. Start Microsoft Visual C#
  2. Create a Windows Application named RealEstate1
  3. To create a new form, on the main menu, click Projects -> Add Windows Form...
  4. Set the Name to PropertyEditor and click Add
  5. Design the form as follows: Control Text Name Other Properties Label Property #: TextBox txtPropertyNumber Modifiers: Public Label Property Type: ComboBox cbxPropertyTypes Modifiers : Public Items : Unknown Single Family Townhouse Condominium Label Address: TextBox txtAddress Modifiers: Public Label City: TextBox txtCity Modifiers: Public Label State: ComboBox cbxStates Modifiers: Public Items: DC MD PA VA WV Label ZIP Code: TextBox txtZIPCode Modifiers: Public Label Bedrooms: TextBox 0 txtBedrooms Modifiers: Public Label Bathrooms: TextBox 1.0 txtBathrooms Modifiers: Public Label Market Value: TextBox 0.00 txtMarketValue Modifiers: Public Button OK btnOK DialogResult: OK Button Cancel btnCancel DialogResult: Cancel Form FormBorderStyle: FixedDialog Text: Altair Realtors - Property Editor StartPosition: CenterScreen AcceptButton: btnOK CancelButton: btnCancel MaximizeBox: False MinimizeBox: False ShowInTaskBar: False
  6. In the Solution Explorer, right-click Form1.cs and click Rename
  7. Type AltairRealtor.cs and press Enter twice (to display that form)
  8. Design the form as follows: Control Text Name Label Property #: TextBox txtPropertyNumber Button Open btnOpen Label Property Type: TextBox txtPropertyType Label Address: TextBox txtAddress Label City: TextBox txtCity Label State: TextBox txtState Label ZIP Code: TextBox txtZIPCode Label Bedrooms: TextBox 0 txtBedrooms Label Bathrooms: TextBox 1.0 txtBathrooms Label Market Value: TextBox 0.00 txtMarketValue Button &New Property... btnNewProperty Button Close btnClose Form FormBorderStyle: FixedDialog Text: Altair Realtors - Property Editor StartPosition: CenterScreen
  9. Save the form

Serialization#

Binary serialization works by processing an object rather than streaming its individual member variables. This means that, to use it, you define an object and initialize it, or "fill" it, with the necessary values and any information you judge necessary. This creates a "state" of the object. It is this state that you prepare to serialize. When you save the object, it is converted into a stream. To perform binary serialization, there are a few steps you must follow. When creating the class whose objects would be serialized, start it with the [Serializable] attribute. Here is an example:

C#
using System;

namespace Cars1
{
    [Serializable]
    public class Car
    {
        public string Make;
        public string Model;
        public uint Year;
        public int Color;
    }
}

Before serializing an object, you should reference the System.Runtime.Serialization.Formatters.Binary namespace. The class responsible for binary serialization is called BinaryFormatter. This class is equipped with two constructors. The default constructor is used to simply create an object. After declaring the variable, to actually serialize an object, call the Serialize() method of the BinaryFormatter class. The method is overloaded with two versions. One of the versions of this method uses the following syntax:

C#
public void Serialize(Stream serializationStream, object graph);

The first argument to this method must be an object of a Stream-based class, such as a FileStream object. The second argument must be the object to serialize. This means that, before calling this method, you should have built the object. Here is an example:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Cars1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            Car vehicle = new Car();
            vehicle.Make  = txtMake.Text;
            vehicle.Model = txtModel.Text;
            vehicle.Year  = uint.Parse(txtYear.Text);
            vehicle.Color = cbxColors.SelectedIndex;

            FileStream stmCar = new FileStream("Car3.car",
                                             FileMode.Create);
            BinaryFormatter bfmCar = new BinaryFormatter();

            bfmCar.Serialize(stmCar, vehicle);
        }
    }
}

Practical Learning: Serializing an Object

  1. To create a new class, on the main menu, click Project -> Add Class...
  2. Set the Name to SampleProperty and click Add
  3. Change the file as follows: using System; using System.Collections.Generic; using System.Text; namespace RealEstate1 { [Serializable] public class SampleProperty { public string PropertyNumber; public string PropertyType; public string Address; public string City; public string State; public int ZIPCode; public short Bedrooms; public float Bathrooms; public double MarketValue; } }
  4. On the main menu, click Windows -> AltairRealtors.cs [Design]
  5. On the form, double-click New Property...
  6. Implement the event as follows: private void btnNewProperty_Click(object sender, EventArgs e) { PropertyEditor editor = new PropertyEditor(); DirectoryInfo dirInfo = Directory.CreateDirectory(@"C:\Altair Realtors\Properties"); Random rnd = new Random(); int left = rnd.Next(100, 999); int right = rnd.Next(100, 999); editor.txtPropertyNumber.Text = left.ToString() + "-" + right.ToString(); if (editor.ShowDialog() == DialogResult.OK) { SampleProperty prop = new SampleProperty(); prop.PropertyNumber = editor.txtPropertyNumber.Text; prop.PropertyType = editor.cbxPropertyTypes.Text; prop.Address = editor.txtAddress.Text; prop.City = editor.txtCity.Text; prop.State = editor.cbxStates.Text; prop.ZIPCode = int.Parse(editor.txtZIPCode.Text); prop.Bedrooms = short.Parse(editor.txtBedrooms.Text); prop.Bathrooms = float.Parse(editor.txtBathrooms.Text); prop.MarketValue = double.Parse(editor.txtMarketValue.Text); string strFilename = dirInfo.FullName + "\\" + editor.txtPropertyNumber.Text + ".prp"; FileStream stmProperty = new FileStream(strFilename, FileMode.Create, FileAccess.Write); BinaryFormatter bfmProperty = new BinaryFormatter(); bfmProperty.Serialize(stmProperty, prop); } }
  7. Return to the form and double-click Close
  8. Implement the event as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
  9. Execute the application and continuously click the New Property button to create the following properties (let the computer specify the property number): Property Type Address City State ZIP Code Beds Baths Market Value Single Family 11604 Aldora Avenue Baltimore MD 21205 5 3.5 325650 Townhouse 495 Parker House Terrace Gettysburg WV 26201 3 2.5 225500 Condominium 5900 24th Street NW #812 Washington DC 20008 1 1.0 388665 Single Family 6114 Costinha Avenue Martinsburg WV 25401 4 3.5 325000 Condominium 10710 Desprello Street #10D Rockville MD 20856 1 1.0 528445
  10. Close the form and return to your programming environment

De-Serialization#

As serialization is the process of storing an object to a medium, the opposite, serialization is used to retrieve an object from a stream. To support this, the BinaryFormatter class is equipped with the Deserialize() method. Like Serialize(), the Deserialize() method is overloaded with two versions. One of them uses the following syntax:

C#
public object Deserialize(Stream serializationStream);

The Deserialize() method accepts a Stream-based object, like FileStream, to locate the data. Since it returns a generic Object, you must cast the result to your specific class type to access the stored values. Here is a sample implementation:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Cars1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            Car vehicle = new Car();
            vehicle.Make  = txtMake.Text;
            vehicle.Model = txtModel.Text;
            vehicle.Year  = uint.Parse(txtYear.Text);
            vehicle.Color = cbxColors.SelectedIndex;

            FileStream stmCar = new FileStream("Car3.car",
                                             FileMode.Create);
            BinaryFormatter bfmCar = new BinaryFormatter();

            bfmCar.Serialize(stmCar, vehicle);
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            FileStream stmCar = new FileStream("Car3.car",
                                             FileMode.Open);
            BinaryFormatter bfmCar = new BinaryFormatter();
            Car vehicle = (Car)bfmCar.Deserialize(stmCar);

            txtMake.Text = vehicle.Make;
            txtModel.Text = vehicle.Model;
            txtYear.Text = vehicle.Year.ToString();
            cbxColors.SelectedIndex = vehicle.Color;
        }
    }
}

Practical Learning: De-Serializing an Object

  1. On the (first) form, double-click the Open button and implement its event as follows: private void btnOpen_Click(object sender, EventArgs e) { DirectoryInfo dirProperties = new DirectoryInfo(@"C:\Altair Realtors\Properties"); FileInfo[] fleProperties = dirProperties.GetFiles(); if (dirProperties.Exists == true) { bool found = false; SampleProperty prop = null; foreach (FileInfo fle in fleProperties) { FileStream stmProperty = new FileStream(fle.FullName, FileMode.Open, FileAccess.Read); BinaryFormatter bfmProperty = new BinaryFormatter(); prop = (SampleProperty)bfmProperty.Deserialize(stmProperty); if (prop.PropertyNumber == txtPropertyNumber.Text) { found = true; } } if (found == true) { txtPropertyType.Text = prop.PropertyType; txtAddress.Text = prop.Address; txtCity.Text = prop.City; txtState.Text = prop.State; txtZIPCode.Text = prop.ZIPCode.ToString(); txtBedrooms.Text = prop.Bedrooms.ToString(); txtBathrooms.Text = prop.Bathrooms.ToString("F"); txtMarketValue.Text = prop.MarketValue.ToString("F"); } else { MessageBox.Show("There is no property with " + "that number in our database"); txtPropertyType.Text = "Unknown"; txtAddress.Text = ""; txtCity.Text = ""; txtState.Text = ""; txtZIPCode.Text = "00000"; txtBedrooms.Text = "0"; txtBathrooms.Text = "0.00"; txtMarketValue.Text = "0.00"; } } }
  2. Execute the application and try opening a previously save property using its number
  3. Close the form and return to your programming environment

SOAP Serialization#

Introduction#

The .NET Framework supports another technique of serialization referred to as SOAP (which stands for Simple Object Access Protocol). This technique is a related to XML but, although we haven't studied XML, you don't need to know anything about it to use SOAP serialization. Practical Learning: Introducing SOAP Serialization

  1. Start a new Windows Application named WattsALoan3
  2. In the Solution Explorer, right-click Form1.cs and click Rename
  3. Type LoanPreparation.cs and press Enter
  4. Design the form as followed: Control Name Text Additional Properties GroupBox Loan Identification Label Prepared &By: TextBox txtEmployeeName Label Customer First Name: TextBox txtCustomerFirstName Label Last Name: TextBox txtCustomerLastName GroupBox Loan Preparation Label Principal: TextBox txtPrincipal 0.00 TextAlign: Right Label Interest Rate: TextBox txtInterestRate 8.25 TextAlign: Right Label % Label Periods: TextBox txtPeriods 1 TextAlign: Text ComboBox cbxPeriods Months Items: Years Months Days GroupBox Results Button btnCalculate Calculate Label Interest Earned: TextBox txtInterestEarned 0.00 TextAlign: Right ReadOnly: True Label Amount Earned: TextBox txtFutureValue 0.00 TextAlign: Right ReadOnly: True GroupBox File Processing Label Loan ID: TextBox txtSave Button &Save btnSave Label Loan ID: TextBox txtOpen Button &Open btnOpen Button btnClose Close
  5. On the form, click the Last Name text box
  6. In the Properties window, click the Events button and double-click Leave
  7. Implement the event as follows: private void txtCustomerLastName_Leave(object sender, EventArgs e) { var Initials = "00"; var FirstName = txtCustomerFirstName.Text; var LastName = txtCustomerLastName.Text; if (LastName.Length == 0) { MessageBox.Show("You must enter a last name"); txtCustomerLastName.Focus(); return; } if (FirstName.Length == 0) Initials = LastName.Substring(0, 1) + "1"; else Initials = FirstName.Substring(0, 1) + LastName.Substring(0, 1); txtSave.Text = Initials; }
  8. Return to the form
  9. On the form, double-click the Calculate button and implement its Click event as follows: private void btnCalculate_Click_1(object sender, EventArgs e) { var Principal = 0.00; var InterestRate = 0.00; var InterestEarned = 0.00; var FutureValue = 0.00; var Periods = 0.00; // Retrieve the value of the principal try { Principal = double.Parse(txtPrincipal.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the principal " + "is not valid.\nPlease try again"); } // Retrieve the interest rate try { InterestRate = double.Parse(txtInterestRate.Text) / 100; } catch (FormatException) { MessageBox.Show("The value you entered for the interest " + "rate is not valid\nPlease try again"); } // Get the number of periods try { if (cbxPeriods.SelectedIndex == 0) // Years Periods = double.Parse(txtPeriods.Text); else if (cbxPeriods.SelectedIndex == 1) // Months Periods = double.Parse(txtPeriods.Text) / 12; else // if (cbxPeriods.SelectedIndex == 2) Days Periods = double.Parse(txtPeriods.Text) / 360; } catch (FormatException) { MessageBox.Show("The value you entered for the number " + "of periods is not valid\nPlease try again"); } var InterestRatePeriods = InterestRate * Periods; var InterestPlus1 = InterestRatePeriods + 1; FutureValue = Principal * InterestPlus1; InterestEarned = FutureValue - Principal; txtInterestEarned.Text = InterestEarned.ToString("F"); txtFutureValue.Text = FutureValue.ToString("F"); }
  10. Execute the application to make sure it is fine
  11. After using it, close the form and return to your programming environment

Serialization With SOAP#

To serialize an object using SOAP, you follow the same steps we reviewed for the binary serialization with one addition: you must add a certain reference. When creating the class whose objects would be serialized, mark it with the [Serializable] attribute. Here is an example:

C#
[Serializable]
public class Car
{
    public string Make;
    public string Model;
    public uint   Year;
    public byte Color;
}

To support SOAP serialization, the .NET Framework provides the SoapFormatter class. This class is defined in the System.Runtime.Serialization.Formatters.Soap namespace that is part of the System.Runtime.Serialization.Formatters.Soap.dll assembly. In order to use The SoapFormatter class, you must reference this assembly. Then, you can create an object and initialize it as you see fit. Before saving it, as always, create a Stream-based object that would indicate the name (and location) of the file and the type of action to perform. Then, declare a SoapFormatter variable using its default constructor. To actually save the object, call the Serialize() method of this class. This method uses the same syntax as that of the BinaryFormatter class: it takes two arguments. The first is a Stream-based object. The second is the object that needs to be serialized. Practical Learning: Serializing With SOAP

  1. To create a new class, on the main menu, click Project -> Add Class...
  2. Set the Name to LoanInformation and click Add
  3. Change the file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WattsALoan3 { [Serializable] public class LoanInformation { public string EmployeeName; public string CustomerFirstName; public string CustomerLastName; public double Principal; public double InterestRate; public double Periods; public int PeriodType; } }
  4. To add SOAP support to your project, on the main menu, click Project -> Add Reference...
  5. In the Add Reference dialog box and in the .NET tab, scroll down and select System.Runtime.Serialization.Formatters.Soap :
  6. Click OK
  7. On the form, double-click the Save button
  8. In the top section of the form, type the following: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Runtime.Serialization.Formatters.Soap;
  9. Scroll down and implement the event as follows: private void btnSave_Click(object sender, EventArgs e) { if (txtSave.Text.Length == 0) { MessageBox.Show("Please enter the customer " + "initials or a name for the loan"); txtSave.Focus(); return; } var infLoan = new LoanInformation(); infLoan.EmployeeName = txtEmployeeName.Text; infLoan.CustomerFirstName = txtCustomerFirstName.Text; infLoan.CustomerLastName = txtCustomerLastName.Text; infLoan.Principal = double.Parse(txtPrincipal.Text); infLoan.InterestRate = double.Parse(txtInterestRate.Text); infLoan.Periods = double.Parse(txtPeriods.Text); infLoan.PeriodType = cbxPeriods.SelectedIndex; var stmLoan = new FileStream(txtSave.Text, FileMode.Create, FileAccess.Write); var sfmLoan = new SoapFormatter(); try { sfmLoan.Serialize(stmLoan, infLoan); txtEmployeeName.Text = ""; txtCustomerFirstName.Text = ""; txtCustomerLastName.Text = ""; txtPrincipal.Text = "0.00"; txtInterestRate.Text = "0.00"; txtPeriods.Text = "0"; cbxPeriods.SelectedIndex = 0; txtFutureValue.Text = "0.00"; txtInterestEarned.Text = "0.00"; txtSave.Text = ""; txtOpen.Text = ""; txtEmployeeName.Focus(); } finally { stmLoan.Close(); } }
  10. Press Ctrl + F5 to execute the application
  11. Create, calculate, and save a few loans
  12. Close the form and return to your programming environment

De-Serialization With SOAP#

De-serialization in soap is performed exactly as done for the binary de-serialization. To support it, the SoapFormatter class is equipped with the Deserialize() method. This method uses the same syntax as its equivalent of the BinaryFormatter class. The approach to use it is also the same. Practical Learning: Deserializing With SOAP

  1. To deserialize, on the form, double-click the Open button and implement its event as follows: private void btnOpen_Click(object sender, EventArgs e) { if (txtOpen.Text.Length == 0) { MessageBox.Show("Please enter a customer's initials or " + "a name given to a previous loan preparation"); txtOpen.Focus(); return; } try { var infLoan = new LoanInformation(); var stmLoan = new FileStream(txtOpen.Text, FileMode.Open, FileAccess.ReadWrite); var sfmLoan = new SoapFormatter(); try { // Open the file and store its values // in the LoanInformation variable infLoan = (LoanInformation)sfmLoan.Deserialize(stmLoan); // Retrive each value and put it in its corresponding control txtEmployeeName.Text = infLoan.EmployeeName; txtCustomerFirstName.Text = infLoan.CustomerFirstName; txtCustomerLastName.Text = infLoan.CustomerLastName; txtPrincipal.Text = infLoan.Principal.ToString("F"); txtInterestRate.Text = infLoan.InterestRate.ToString("F"); txtPeriods.Text = infLoan.Periods.ToString(); cbxPeriods.SelectedIndex = infLoan.PeriodType; // Since we didn't save the calculated values, // call the Click event of the Calculate button btnCalculate_Click(sender, e); } finally { stmLoan.Close(); } } catch (FileNotFoundException) { MessageBox.Show("There is no file with that name"); } }
  2. Return to the form and double-click the Close button
  3. Implement its Click event as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
  4. Press Ctrl + F5 to execute the application
  5. Enter the initials of a previously created loan and click Open
  6. Close the form and return to your programming environment

Details on Serialization#

Partial Serialization#

In the examples we have used so far, we were saving the whole object. You can make it possible to save only some parts of the class. When creating a class, you can specify what fields would be serialized and which ones would not be. To specify that a member cannot be saved, you can mark it with the [NonSerialized] attribute. Here is an example:

C#
[Serializable]
public class Car
{
    public string Make;
    public string Model;

    // Because the value of a car can change,
    // there is no reason to save it
    [NonSerialized]
    public decimal Value;
    public uint Year;
    public byte Color;
}

After creating the class, you can declare a variable of it and serialize it, using either the binary or the SOAP approach. You can then retrieve the object and its values, using any of the techniques we learned earlier.

Implementing a Custom Serialized Class#

To support serialization, the .NET Framework provides the ISerializable interface. You can create a class that implements this interface to customize the serialization process. Even if you plan to use this interface, the class you create must be marked with the [Serializable] attribute.

.NET Built-In Serialized Classes#

The .NET Framework is filled with many classes ready for serialization. To know that a class is ready for serialization, when viewing its documentation either in the MSDN web site or in the help documentation, check that it is marked with the [SerializableAttribute]. Here is an example of such as class:

While some classes include built-in methods for saving objects directly, others require you to define a class with the [Serializable] attribute before passing its instances to the .NET serialization classes.

Exercises#

Altair Realtors#

  1. Open the Altair Realtors application from this lesson
  2. Configure the main form for printing by allowing the user to print the property that is currently displaying

Watts A Loan#

  1. Open the Watts A Loan application from this lesson
  2. Configure the main form to allow the user to print the loan preparation

Home Copyright © 2008 C# Key