Skip to content

Commit 038ec79

Browse files
rstamcraiggwilson
authored andcommitted
Implemented CSHARP-496. The BsonValue implementation of IConvertible.ToString can now convert BsonObjectIds to string.
1 parent 7307727 commit 038ec79

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

Bson/ObjectModel/BsonValue.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1528,6 +1528,7 @@ string IConvertible.ToString(IFormatProvider provider)
15281528
case BsonType.Double: return Convert.ToString(this.AsDouble, provider);
15291529
case BsonType.Int32: return Convert.ToString(this.AsInt32, provider);
15301530
case BsonType.Int64: return Convert.ToString(this.AsInt64, provider);
1531+
case BsonType.ObjectId: return this.AsObjectId.ToString();
15311532
case BsonType.String: return this.AsString;
15321533
default: throw new InvalidCastException();
15331534
}
@@ -1542,6 +1543,7 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider)
15421543
case BsonType.Double: return Convert.ChangeType(this.AsDouble, conversionType, provider);
15431544
case BsonType.Int32: return Convert.ChangeType(this.AsInt32, conversionType, provider);
15441545
case BsonType.Int64: return Convert.ChangeType(this.AsInt64, conversionType, provider);
1546+
case BsonType.ObjectId: return Convert.ChangeType(this, conversionType, provider);
15451547
case BsonType.String: return Convert.ChangeType(this.AsString, conversionType, provider);
15461548
default: throw new InvalidCastException();
15471549
}

BsonUnitTests/ObjectModel/BsonValueIConvertibleTests.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ public void TestBsonNull()
306306
[Test]
307307
public void TestBsonObjectId()
308308
{
309-
var value = BsonObjectId.Empty;
309+
var value = new BsonObjectId(ObjectId.Parse("0102030405060708090a0b0c"));
310310
Assert.Throws<InvalidCastException>(() => Convert.ToBoolean(value));
311311
Assert.Throws<InvalidCastException>(() => Convert.ToByte(value));
312312
Assert.Throws<InvalidCastException>(() => Convert.ToChar(value));
@@ -318,7 +318,8 @@ public void TestBsonObjectId()
318318
Assert.Throws<InvalidCastException>(() => Convert.ToInt64(value));
319319
Assert.Throws<InvalidCastException>(() => Convert.ToSByte(value));
320320
Assert.Throws<InvalidCastException>(() => Convert.ToSingle(value));
321-
Assert.Throws<InvalidCastException>(() => Convert.ToString(value));
321+
Assert.AreEqual("0102030405060708090a0b0c", Convert.ToString(value));
322+
Assert.AreEqual("0102030405060708090a0b0c", ((IConvertible)value).ToType(typeof(string), null));
322323
Assert.Throws<InvalidCastException>(() => Convert.ToUInt16(value));
323324
Assert.Throws<InvalidCastException>(() => Convert.ToUInt32(value));
324325
Assert.Throws<InvalidCastException>(() => Convert.ToUInt64(value));

0 commit comments

Comments
 (0)