Artur Tadrała
Artur Tadrała

Reputation: 143

How does F# know that bitArray elements are bool while enumerating in seq builder?

    seq{
        for bit in BitArray(10) do 
        yield bit
    }

bit is of bool type. I checked with ILSpy and there's an explicit cast added in one of closures generated.

BitArray implements only plain (not generic) IEnumerable. How does F# know that it's a bool?

Upvotes: 13

Views: 316

Answers (1)

Ringil
Ringil

Reputation: 6537

According to the F# 4.1 specification's Section 6.5.6 Sequence Iteration Expressions, F# does casting even for a non-generic IEnumerable if the IEnumerable has an Item property with a non-object type (highlighting mine):

An expression of the following form is a sequence iteration expression:

for pat in expr1 do expr2 done

The type of pat is the same as the return type of the Current property on the enumerator value. However, if the Current property has return type obj and the collection type ty has an Item property with a more specific (non-object) return type ty2, type ty2 is used instead, and a dynamic cast is inserted to convert v.Current to ty2.

If we look at the source code for BitArray, we see that it does indeed have an Item property with type bool:

public bool this[int index] {
        get {
            return Get(index);
        }
        set {
            Set(index,value);
        }
}

Thus, F# will explicitly cast to bool while iterating.

Upvotes: 13

Related Questions