Greg R
Greg R

Reputation: 1691

Using Dictionary in MonoTouch

I am very confused on the MonoTouch dictionary limitation: http://docs.xamarin.com/ios/about/limitations#Value_types_as_Dictionary_Keys

My understanding that code like this is not allowed:

var foo = new Dictionary<int, int>();

But I see code in books like this, which doesn't make sense:

protected Dictionary<int, CustomCellController> _cellControllers = new Dictionary<int, CustomCellController>();

Also, someone posted that if you use nullable types, it convers the values into reference so the following works (as long as the key is not null):

var foo = new Dictionary<int?, int?>();

That also doesn't make sense, because nullable types are structs which are value types.

So what are the real rules about using dictionaries on a device?

Upvotes: 2

Views: 855

Answers (1)

poupou
poupou

Reputation: 43553

Since no JITin is allowed on devices all code must be compiled with the AOT (ahead of time) compiler.

My understanding that code like this is not allowed:

This limitation is about the difficulties, for the AOT compiler, of determining what will be used at runtime. Such code might work and you'll see such code in samples - but it can also fail depending on what you do with the code (creating a Dictionary is not the problem).

So what are the real rules about using dictionaries on a device?

Using value-types means that the generated code cannot be shared (like it can for reference types). E.g. Using a generic Dictionary with int and long requires separate code, while the same code can be shared for string and CustomCellController.

Finding what Dictionary<int,int> needs is not the issue (it's pretty clear). However it's often in the internals that things gets complicated, e.g. ensuring the right KeyValuePair is generated. Nested generics are also hard to get right.

This is why the first general workaround is to try to hint the AOT compiler about what's needed. If the AOT compiler can find code that requires it to generate what's needed then it will be available at runtime.

The next workaround is to try to use a reference type (e.g. a string) instead of the value-type (since that case is simpler to handle for the AOT compiler).

Finally the AOT compiler is getting better (by each release) and works continues to reduce this (and other) limitation(s). So what you read here might not apply in 3, 6, 12 months...

Upvotes: 2

Related Questions