I need to interface with a function that receives an object of type NSDictionary<NSString, NSObject>
in Xamarin.
First, I don't understand the syntax.
What exactly is a NSDictionary<NSString, NSObject>
type object?
I know there is NSDictionary type and I know how to create one and set keys and values, but what is NSDictionary<?,?>
? Is it suppose to be some sort of a special tuple?
Second, how do I create such an object and define the key and associated object?
NSDictionary<TKey, TValue>
is just a generic version of NSDictionary
. This means that the keys are all of the type TKey
(in your case NSString
) and the values are all of type TValue
(in your case NSObject.
). This provides more type safety, because e.g. you can't add integers as keys. The underlying iOS object is still a NSDictionary
. This class is kind of "syntactic sugar", because we are used to strict typing in C# and want to use it where ever possible.
You can create it with a constructor. It has multiple constructors. E.g. NSDictionary(TKey[] keys, TValue[] values)
is taking the keys and values as parameters and creates NSDictionary
of it.
var keys = new[]
{
new NSString("key1"),
new NSString("key2"),
new NSString("key3"),
new NSString("key4")
};
var objects = new NSObject[]
{
// don't have to be strings... can be any NSObject.
new NSString("object1"),
new NSString("object1"),
new NSString("object1"),
new NSString("object1")
};
var dicionary = new NSDictionary<NSString, NSObject>(keys, objects);
On Xamarin.Mac, and following Sven-Michael Stübe, it can be:
var dictionary = new NSDictionary(
new NSString("key1"), new NSString("object1"),
new NSString("key2"), new NSString("object2")
);
Probably Xamarin.iOS too but I didn't tested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With