Click here to Skip to main content
15,895,370 members
Articles / Programming Languages / C#

Custom Serialization Example

Rate me:
Please Sign up or sign in to vote.
4.36/5 (9 votes)
9 Jan 2008CPOL10 min read 97.7K   1.2K   39  
An example of implementing custom serialization, how to serialize a collection, and using a File Serialization utility class
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace MyUtilities
{
    [Serializable]
    public class Car : ISerializable
    {
        private readonly string _make;
        private readonly string _model;
        private readonly int _year;
        private Owner _owner = null; //this is variable and can change

        private Car() {} //default ctor not valid - we want to enforce initializing our data
        public Car( string make, string model, int year )
        {
            _make = make;
            _model = model;
            _year = year;
        }

        public Owner Owner
        {
            get { return _owner; }
            set { _owner = value; }
        }
        public string Make
        {
            get { return _make; }
        }
        public string Model
        {
            get { return _model; }
        }
        public int Year
        {
            get { return _year; }
        }

        //note: this is private to control access; the serializer can still access this constructor
        private Car( SerializationInfo info, StreamingContext ctxt )
        {
            this._make = info.GetString("Make");
            this._model = info.GetString("Model");
            this._year = info.GetInt32("Year");
            this._owner = (Owner)info.GetValue("Owner", typeof(Owner));
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public void GetObjectData( SerializationInfo info, StreamingContext ctxt )
        {
            info.AddValue("Make", this._make);
            info.AddValue("Model", this._model);
            info.AddValue("Year", this._year);
            info.AddValue("Owner", this._owner, typeof(Owner));
        }
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions