As Monobjc provides wrappers around native objects, the casting of objects (upcasting and downcasting) cannot be done with the .NET operators. Every managed wrapper can be cast to another wrapper but the hierarchy checks are made at runtime and not at compile time.
A strict casting operation is done as follow. Note that a failure will raise an exception. Here are some examples :
// A strict cast from Id to NSString NSString identifier = instance.CastTo<NSString>(); // A strict cast from Id to NSButton NSButton button = sender.CastTo<NSButton>();
You can also perform a fail-safe cast, when you do not know in advance the type of the wrapper, or if you want the cast not to be strict:
// A fail-safe cast from Id to NSButton NSButton button = sender.CastAs<NSButton>();
You can perform casting (either strict or fail-safe) on null references with the following methods:
// A strict cast from Id to NSButton, that works even is sender is null NSButton button = sender.SafeCastTo<NSButton>(); // A fail-safe cast from Id to NSButton, that works even is sender is null NSButton button = sender.SafeCastAs<NSButton>();
The Monobjc bridge provides implicit conversion when dealing with basic types such as String or numbers. The implicite conversion reduces the code needed to go back and forth between .NET and Objective-C. With implicit conversion you can :
Monobjc.Foundation.NSStringcan be implictly casted to
Monobjc.Foundation.NSNumbercan be implictly casted from
- Other implicit conversions will be added as the framework integration goes on.