Source Generated Classes and Nullability in Realm .NET
Rate this article
The latest releases of Realm .NET have included some interesting updates that we would love to share — in particular, source generated classes and support for nullability annotation.
The migration to the new source generated classes is quite straightforward. All you need to do is:
- Declare the Realm classes as
partial, including all the eventual containing classes.
- Swap out the base Realm classes (
AsymmetricObject) for the equivalent interfaces (
partialinstead of overriding them, if they are used.
The property definition remains the same, and the source generator will take care of adding the full implementation of the interfaces.
To give an example, if your model definition looks like this:
This is how it should look like after you migrated it:
The classic Realm model definition is still supported, but it will not receive some of the new updates, such as the support for nullability annotations, and will be phased out in the future.
introduced full support for nullability annotations in the model definition for source generated classes. This allows you to use Realm models as usual when nullable context is active, and removes the need to use the
Requiredattribute to indicate required properties, as this information will be inferred directly from the nullability status.
To sum up the expected nullability annotations:
- Value type properties, such as
int, can be declared as before, either nullable or not.
byteproperties now cannot be decorated anymore with the
Requiredattribute, as this information will be inferred from the nullability. If the property is not nullable, then it is considered equivalent as declaring it with the
- Collections (list, sets, dictionaries, and backlinks) cannot be declared nullable, but their parameters may be.
- Properties that link to a single Realm object are inherently nullable, and thus the type must be defined as nullable.
- Lists, sets, and backlinks of objects cannot contain null values, and thus the type parameter must be non-nullable.
- Dictionaries of object values can contain null, and thus the type parameter must be nullable.
Defining the properties with a different nullability annotation than what has been outlined will raise a diagnostic error. For instance:
We realize that some developers would prefer to have more freedom in the nullability annotation of object properties, and it is possible to do so by setting
realm.ignore_objects_nullability = truein a global configuration file (more information about this can be found in the ). If this option is enabled, all the object properties (including collections) will be considered valid, and the nullability annotations will be ignored.