2
Answers

Generic lists and foreach type safety

Jud White

Jud White

17y
2.7k
1

Does anyone have a suggestion to make this code more type safe? Ideally I'd like to get a compile error on the foreach below, forcing myself to use the interface instead of the class. Maybe this isn't possible but I'm open to suggestions to get the type safety accomplished.

public class ManagementEntity : IManagementEntity
{
}

public static void Delete(IEnumerable<IManagementEntity> list)
{
    Guard.ArgumentNotNull(list, "list");

    foreach (ManagementEntity item in list) // <- use the interface instead!
    {
    }
}

The list is IEnumerable<IManagementEntity>, so when doing foreach ideally I'd like to constrain to IManagementEntity.

The problem is when you iterate using a variable of a type that implements the interface, you're not guaranteed the actual object is what your iterator is (expected) - the fact this is allowed is the problem. What I'm looking for is a way to increase type safety to catch these problems at compile time. There's no changing the way "foreach" works with generics, but if there's a truly type safe way I'd like to use that.

Thanks for your answers.

Answers (2)