dotnet / dotnet/macios

Iterating over generic NSArrays is awkward

Open
#16,537 0 comments 6 reactions 0 assignees View on GitHub
breaking-change enhancement
Dominant language
C#
Stars
2.9k
Forks
576
Avg merge
2d 12h
Merged PRs (30d)
123

Description

Iterating over generic collection classes has become somewhat awkward.

Example:

```cs
var x = new NSArray ();
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:

```cs
var x = new NSArray ();
foreach (var item in (IEnumerable) x) {
}
```

This started happening with https://github.com/xamarin/xamarin-macios/pull/16252, where made the non-generic `NSArray` class implement the `IEnumerable` interface, which made the generic `NSArray` implement both `IEnumerable` and `IEnumerable` (and this error).

A potential solution would be to switch the inheritance chain:

```cs
class NSArray : NSObject, IEnumerable where T: class, INativeObject {}
class NSArray : NSArray {}
```

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)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.