Avoid invalid cast when generating foreach loops