{"record":{"id":"66edb447978f8ede","repo":"JamesNK/Newtonsoft.Json","slug":"an-objectid-must-be-12-bytes","errorCode":null,"errorMessage":"An ObjectId must be 12 bytes","messagePattern":"An ObjectId must be 12 bytes","errorType":"validation","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Bson/BsonObjectId.cs","lineNumber":54,"sourceCode":"    [Obsolete(\"BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.\")]\n    public class BsonObjectId\n    {\n        /// <summary>\n        /// Gets or sets the value of the Oid.\n        /// </summary>\n        /// <value>The value of the Oid.</value>\n        public byte[] Value { get; }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"BsonObjectId\"/> class.\n        /// </summary>\n        /// <param name=\"value\">The Oid value.</param>\n        public BsonObjectId(byte[] value)\n        {\n            ValidationUtils.ArgumentNotNull(value, nameof(value));\n            if (value.Length != 12)\n            {\n                throw new ArgumentException(\"An ObjectId must be 12 bytes\", nameof(value));\n            }\n\n            Value = value;\n        }\n    }\n}","sourceCodeStart":36,"sourceCodeEnd":60,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Bson/BsonObjectId.cs#L36-L60","documentation":"Thrown by the BsonObjectId constructor when the supplied byte array is not exactly 12 bytes long. A MongoDB ObjectId is defined as a fixed 12-byte value (4-byte timestamp, 5-byte random, 3-byte counter), so any other length is invalid. This is an ArgumentException from BsonObjectId.cs:54.","triggerScenarios":"Calling `new BsonObjectId(bytes)` with a byte array whose Length is not 12. Commonly happens when deserializing an OID from a hex string that was converted with the wrong encoding, or when passing a 16-byte Guid or a truncated/padded value.","commonSituations":"Parsing a 24-char hex string but forgetting to decode it (passing the string's ASCII bytes, 24 bytes). Passing a Guid.ToByteArray() (16 bytes) directly. Reading a corrupt or partial BSON stream whose OID field is not 12 bytes. Using the obsolete in-box BsonObjectId instead of the dedicated BSON package's ObjectId type.","solutions":["Ensure the byte array passed to the BsonObjectId constructor is exactly 12 bytes.","If you have a 24-character hex string, convert it with the correct decoder (2 hex chars -> 1 byte = 12 bytes), not Encoding.ASCII.GetBytes.","If you have a Guid, do not pass it directly; map the relevant 12 bytes explicitly.","Switch to the dedicated Newtonsoft.Json.Bson package which has its own ObjectId handling."],"exampleFix":"// before: passing a hex string's ASCII bytes (24 bytes)\nvar oid = new BsonObjectId(Encoding.ASCII.GetBytes(\"507f1f77bcf86cd799439011\"));\n\n// after: decode hex to 12 bytes\nbyte[] bytes = Enumerable.Range(0, 24)\n    .Where(i => i % 2 == 0)\n    .Select(i => Convert.ToByte(hex.Substring(i, 2), 16))\n    .ToArray();\nvar oid = new BsonObjectId(bytes);","handlingStrategy":"validation","validationCode":"byte[] bytes = GetOidBytes();\nif (bytes == null || bytes.Length != 12)\n    throw new ArgumentException($\"ObjectId must be 12 bytes, got {bytes?.Length ?? 0}\");\nvar oid = new BsonObjectId(bytes);","typeGuard":"static bool IsValidObjectId(byte[] b) => b != null && b.Length == 12;","tryCatchPattern":"try { return new BsonObjectId(bytes); }\ncatch (ArgumentException ex) when (ex.Message.Contains(\"12 bytes\"))\n{\n    throw new InvalidDataException($\"Bad ObjectId length: {bytes?.Length}\", ex);\n}","preventionTips":["Always decode 24-char hex strings to exactly 12 bytes before constructing a BsonObjectId.","Never pass Guid.ToByteArray() (16 bytes) directly as an ObjectId.","Pre-validate length to give a clearer error than the library's generic message."],"tags":["bson","objectid","argument","validation"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}