Code sample WithTransaction C# docs wrong?

Hi, I’m referring to this code sample

Session.withTransaction() — MongoDB Manual

var session = db.getMongo().startSession( { readPreference: { mode: "primary" } } );
session.withTransaction( async() => {
   const sessionCollection = session.getDatabase(dbName).getCollection(collectionName);
   // Check needed values
   var checkFromAccount = sessionCollection.findOne(
      {
         "customer": fromAccount,
         "balance": { $gte: transferAmount }
      }
   )
   if( checkFromAccount === null ){
      throw new Error( "Problem with sender account" )
   }
   var checkToAccount = sessionCollection.findOne(
      { "customer": toAccount }
   )
   if( checkToAccount === null ){
      throw new Error( "Problem with receiver account" )
   }
   // Transfer the funds
   sessionCollection.updateOne(
      { "customer": toAccount },
      { $inc: { "balance": transferAmount } }
   )
   sessionCollection.updateOne(
      { "customer": fromAccount },
      { $inc: { "balance": -1 * transferAmount } }
   )
}

This don’t seem to be able to compile, TResult is unknown. I need to add a return String.Emptty to compile, which seems odd.

The provided code is a mongosh snippet, which is written in JavaScript. You indicated that you are working with the .NET/C# Driver. Please see Drivers API for Transactions and make sure you select C# as your language in the top right corner of the page. Hope that helps!

Sincerely,
James

1 Like

I used the c# version, of course. I pasted the java script version. It doesn’t compile without the return String.Empty

using (IClientSessionHandle session = await MongoClientSystem.StartSessionAsync ().ConfigureAwait (false))
{
    await session.WithTransactionAsync (async (session, cancellationToken) =>
    {
			// blah
 //THIS IS NEED TO COMPILE
			return String.Empty;
	})
    .ConfigureAwait (false);
}

Please provide the URL that contains the provided code sample as I am unable to locate it in our C# transaction examples. In particular MongoClientSystem is not a class in the .NET/C# Driver and this appears to be third-party code.

Sincerely,
James

That sample is mine. You don’t have a c# sample that’s why I linked in the javascript version. It is to show why you need a String.Empty return to be able to compile in C# when javascript version don’t.

Thank you for patiently explaining the issue. I believe that I understand the problem now. JavaScript allows an implicit null return whereas C# does not. And because WithTransactionAsync returns a TResult, you must provide a return type to make the C# compiler happy even if you don’t use the return value. This is unfortunately a limitation of the C# language. We will consider adapting this guidance into future C# transaction examples. We appreciate your feedback.

1 Like