Search code examples
c#castingwarnings

C# compiler warnings about implicit casts in foreach loop (IDE0220)


As a simplified example of my problem, I've got an array of ISomeType, and I want to loop over all the elements in that array that are actually MyType, but I'm getting IDE0220 warnings "Add explicit cast in foreach loop" that I don't think apply. Here's a code example:

public interface ISomeType {
    void DoThing();
}

public class MyType: ISomeType {
    void DoThing() { /* do something */ }
    void DoMyTypeThing() { /* do something specific to MyType */ }
}

public class YourType: ISomeType {
    void DoThing() { /* do something */ }
    void DoMyTypeThing() { /* do something specific to MyType */ }
}

ISomeType[] maybeMyTypes = [new MyType()];


// I get the error on this line because I cast the element into `MyType`
foreach (MyType foobar in maybeMyTypes.Where(i => i.GetType() == typeof(MyType))) {
    // use the MyType methods availbale on foobar
}

The compiler complains that it implicitly casts the elements of maybeFooBars into MyType, and that this can fail at runtime, so I should be explicit about the cast:

// Code with violations.
var list = new List<object>();
foreach (string item in list) { }

// Fixed code.
var list = new List<object>();
foreach (string item in list.Cast<string>())

Could my code actually fail at runtime, since I'm checking the type and only implicitly casting if the type is correct? Or is the C# compiler not smart enough to see that I've guarded against the types being incorrect?


Solution

  • .Where(i => i.GetType() == typeof(MyType)) won't tell the compiler that you're dealing with only MyType members. For that you'll want OfType instead. So you'll be using it like

    foreach (MyType foobar in maybeMyTypes.OfType<MyType>()) {
        // use the MyType methods availbale on foobar
    }