Skip to content

Commit 2ecfe93

Browse files
committed
CSHARP-1625: Added TryParse to BsonDocument.
1 parent ee79712 commit 2ecfe93

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/MongoDB.Bson/ObjectModel/BsonDocument.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,26 @@ public static BsonDocument Parse(string json)
386386
}
387387
}
388388

389+
/// <summary>
390+
/// Tries to parse a JSON string and returns a value indicating whether it succeeded or failed.
391+
/// </summary>
392+
/// <param name="s">The JSON string.</param>
393+
/// <param name="result">The result.</param>
394+
/// <returns>Whether it succeeded or failed.</returns>
395+
public static bool TryParse(string s, out BsonDocument result)
396+
{
397+
try
398+
{
399+
result = Parse(s);
400+
return true;
401+
}
402+
catch
403+
{
404+
result = null;
405+
return false;
406+
}
407+
}
408+
389409
// public methods
390410
/// <summary>
391411
/// Adds an element to the document.

tests/MongoDB.Bson.Tests/ObjectModel/BsonDocumentTests.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1373,6 +1373,30 @@ public void TestTryGetValue()
13731373
Assert.Equal(1, value.AsInt32);
13741374
}
13751375

1376+
[Fact]
1377+
public void TestTryParse_success()
1378+
{
1379+
var s = "{ x : 1 }";
1380+
BsonDocument result;
1381+
1382+
var success = BsonDocument.TryParse(s, out result);
1383+
1384+
success.Should().BeTrue();
1385+
result.Should().Be(new BsonDocument("x", 1));
1386+
}
1387+
1388+
[Fact]
1389+
public void TestTryParse_failure()
1390+
{
1391+
var s = "{ ...";
1392+
BsonDocument result;
1393+
1394+
var success = BsonDocument.TryParse(s, out result);
1395+
1396+
success.Should().BeFalse();
1397+
result.Should().BeNull();
1398+
}
1399+
13761400
private void AssertAreEqual(string expected, byte[] actual)
13771401
{
13781402
StringBuilder sb = new StringBuilder();

0 commit comments

Comments
 (0)