MaxDepth Option

Represents an option to specify the maximum depth of nested objects during serialization or deserialization.

Namespace

System.Runtime.Serialization.Options

Syntax

public sealed class MaxDepth : Attribute

Description

The MaxDepth attribute is used to control the maximum level of nesting that the serializer will traverse when serializing or deserializing an object graph. This is particularly useful for preventing infinite loops or excessively deep object structures that could lead to performance issues or stack overflows.

When this attribute is applied to a class, property, or field, the serializer will respect the specified depth limit. If the object graph exceeds this limit during serialization, an exception might be thrown (depending on the serializer's configuration). During deserialization, exceeding the depth limit may result in truncated data or an error.

Usage

The MaxDepth attribute can be applied to classes, properties, or fields to define the serialization depth for that specific member or the entire type.

Example: Applying MaxDepth to a Class

[DataContract]
[MaxDepth(5)]
public class TreeNode
{
    [DataMember]
    public string NodeName { get; set; }

    [DataMember]
    public List<TreeNode> Children { get; set; }
}

In this example, the TreeNode class and its descendants will be serialized up to a maximum depth of 5. If a TreeNode object has children that would result in a nesting depth greater than 5, the serialization process will stop at that point.

Example: Applying MaxDepth to a Property

[DataContract]
public class Document
{
    [DataMember]
    public string Title { get; set; }

    [DataMember]
    [MaxDepth(3)]
    public Section[] Sections { get; set; }
}

Here, the Sections array within the Document will be serialized with a depth limit of 3, independent of any other depth limits that might be applied elsewhere.

Parameters

The MaxDepth attribute takes one constructor parameter:

Parameter Type Description
depth int The maximum depth to allow for serialization. Must be a non-negative integer. A value of 0 typically means no limit (or the default limit).

Remarks

  • This attribute is part of the .NET Serialization framework and is often used in conjunction with DataContractAttribute, DataMemberAttribute, and KnownTypeAttribute.
  • The interpretation of MaxDepth may vary slightly depending on the specific serializer implementation (e.g., DataContractSerializer, NetDataContractSerializer).
  • Setting a very low MaxDepth can prevent complex object graphs from being fully serialized or deserialized.
  • Ensure that the depth value is appropriate for the expected structure of your data to avoid unexpected behavior.

See Also