Explicit Casting
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>();
Safe Casting
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>();
Implicit Casting
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.NSString
can be implictly casted toSystem.String
.Monobjc.Foundation.NSNumber
can be implictly casted fromchar
,bool
,short
,int
,uint
,long
orulong
types.- Other implicit conversions will be added as the framework integration goes on.