replace hack with dynamic_cast with Reference::castTo