Skip to content

Need an API to get the 'iteration type' of a type. #77926

@CyrusNajmabadi

Description

@CyrusNajmabadi

Background and Motivation

The IDE has a lot of code for dealing with collection expressions, and just normal collection types, especially around trying to manipulate them and determine if a change from a non-collection to a collection will be legal. This is challenging as we need to ultimately figure out what the starting iteration type is, as well as the final collection-element type, and if things like the elements will be legal given that type.

Determining a iteration type is non trivial. Including having to special case a bunch of types. Having to figure out the 'enumerator' pattern if it is there. Having to handle inline arrays. Having to handle spans. Handling IEnumerable, etc. etc.

The IDE has hacked up a bunch of heuristics. But we really need a concrete way of answering this for real.

Proposed API

Either:

// In MS.CA.dll

namespace MS.CA;

public class SemanticModel
{
    // This is the iteration type that is used in C# foreach, and VB `for each`
    // null-return if cannot be determined.
    public ITypeSymbol? GetIterationType(
        int position, ITypeSymbol type, CancellationToken cancellationToken = default);
}

This API is defined on top of the SemanticModel, along with a position, because extension-methods may be involved in determining the element type.

--

Note: this likely will utilize

internal bool TryGetCollectionIterationType(SyntaxNode syntax, TypeSymbol collectionType, out TypeWithAnnotations iterationType)
to implement this functionality.

Note that the syntax node here is used to just get the right binder.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-CompilersConcept-APIThis issue involves adding, removing, clarification, or modification of an API.Feature Requestapi-approvedAPI was approved in API review, it can be implemented

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions