wcf DataContractSerializer is an Opt-In and Opt-Out serializer. What is opt out serializer


Example

Below code represents an example of Opt-Out approach using Serializable and NonSerialized attributes.

/// <summary>
/// Represents a student.
/// </summary>
[Serializable]
public class Student
{
    /// <summary>
    /// Gets or sets student number.
    /// </summary>
    public string StudentNumber { get; set; }

    /// <summary>
    /// Gets or sets first name.
    /// </summary>
    public string FirstName { get; set; }

    /// <summary>
    /// Gets or sets last name.
    /// </summary>
    public string LastName { get; set; }

    /// <summary>
    /// Gets or sets marks obtained.
    /// </summary>
    [NonSerialized]
    public string MarksObtained { get; set; }
}

/// <summary>
/// A service that provides the operations for student.
/// </summary>
[ServiceContract]
public interface IStudentService
{
    //Service contract code here. Example given.
    
    /// <summary>
    /// Adds a student into the system.
    /// </summary>
    /// <param name="student">Student to be added.</param>
    [OperationContract]
    void AddStudent(Student student);
}

In above example, we explicitly marked MarksObtained property as [NonSerialized] attribute, so it will be ignored except the others. Hope this helps!