Docs Menu

Docs HomeDevelop ApplicationsAtlas Device SDKs

Call a Function - .NET SDK

On this page

  • Call a Function by Name

The examples in this section demonstrate calling a Realm Function named sum that takes two arguments, adds them, and returns the result:

// sum: adds two numbers
exports = function(a, b) {
return a + b;
};

Note

Authenticate First

You call Functions on a User object, so before calling any function, you must authenticate a user.

Important

Make sure to sanitize client data to protect against code injection when using Functions.

To execute a function from the .NET SDK, use the Functions.CallAsync() method on the User object, passing in the name of the function as the first parameter and the arguments as the remaining parameters:

var bsonValue = await
user.Functions.CallAsync("sum", 2, 40);
// The result must now be cast to Int32:
var sum = bsonValue.ToInt32();
// Or use the generic overloads to avoid casting the BsonValue:
sum = await
user.Functions.CallAsync<int>("sum", 2, 40);

Note

The CallAsync() method returns a single BsonValue object, which you can deserialize after calling the function or by using the the generic overload. Both of these approaches to deserialization are shown in the code above.

A BsonValue object can hold a single primitive value (as shown in the example above), or hold a complete BSON document. If you have a class that maps to the returned object, you can deserialize to that class by using the generic overload. For example, the following code calls a function that returns an object from a collection of "RealmTasks". Since we know the shape of the returned object, we we can deserialize the BsonValue to a class that we have created, and then we have access to the properties and methods on that object:

var item = await user.Functions.CallAsync<MyClass>
("getItem", "5f7f7638024a99f41a3c8de4");
var name = item.Name;
← Connect to an Atlas App Services Backend - .NET SDK