Is there a safe way to convert NSMutableDictionary<TKey, TValue> to NSDictionary<TKey, TValue> without allocating a new object?

Oliver Brown 1 Reputation point
2021-08-11T09:12:55.067+00:00

The iOS types, in Objective-C are as follows

NSMutableDictionary inherits from NSDictionary.

Objective-C has lightweight generics, providing NSMutableDictionary<TKey, TValue> and NSDictionary<TKey, TValue>. These are implemented via type erasure, so at runtime you are free to cast between them and everything will work (at the risk of runtime errors if you get a type you did not expect).

The Xamarin binding has:

NSMutableDictionary inherits from NSDictionary
NSDictionary<TKey, TValue> inherits from NSDictionary
NSMutableDictionary<TKey, TValue> inherits from NSMutableDictionary

This means from .NET's type system's point of view, NSMutableDictionary<TKey, TValue> and NSDictionary<TKey, TValue> are not compatible.

Is there a way to get an NSDictionary<TKey, TValue> from an NSMutableDictionary<TKey, TValue> without creating a new dictionary? The best I could see is Unsafe.As, but I don't actually know if that does what I want.

Oliver

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,293 questions
{count} votes