Skip to content

Iterating over generic NSArrays is awkward #16537

@rolfbjarne

Description

@rolfbjarne

Iterating over generic collection classes has become somewhat awkward.

Example:

var x = new NSArray<NSString> ();
foreach (var item in x) {
}

Gives a compiler error:

error CS1640: foreach statement cannot operate on variables of type 'NSArray' because it implements multiple instantiations of 'IEnumerable'; try casting to a specific interface instantiation

and something like this is required instead:

var x = new NSArray<NSString> ();
foreach (var item in (IEnumerable<NSString>) x) {
}

This started happening with #16252, where made the non-generic NSArray class implement the IEnumerable<NSObject> interface, which made the generic NSArray<T> implement both IEnumerable<NSObject> and IEnumerable<T> (and this error).

A potential solution would be to switch the inheritance chain:

class NSArray<T> : NSObject, IEnumerable<T> where T: class, INativeObject {}
class NSArray : NSArray<NSObject> {}

but this would be a breaking change, so I'm marking this for XAMCORE_5_0.

Also if we do this change for NSArray, we should do the same for all the other generic collection classes (NSMutableArray, NS[Mutable][Ordered]Set, NS[Mutable]Dictionary)

Metadata

Metadata

Assignees

No one assigned

    Labels

    breaking-changeIf an issue or a pull request represents a breaking changeenhancementThe issue or pull request is an enhancement

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions