Cannot cast RuntimeAnimatorController to AnimatorOverrideController

I want to use AnimatorOverrideController to change the animation at run time through script. I tried this which gives and InvalidCastException:

RuntimeAnimatorController controller = animator.runtimeAnimatorController;
AnimatorOverrideController overrideController = (AnimatorOverrideController)controller;

And this makes controller to null

RuntimeAnimatorController controller = animator.runtimeAnimatorController;
AnimatorOverrideController overrideController = controller as AnimatorOverrideController;

That’s what i found in all the code samples everywhere. Not sure what is going wrong here. I am using Unity 5.5

You need to create a new AnimatorOverrideController, or use an AnimatorOverrideController asset, not cast your current AnimatorController to an AnimatorOverrideController.

I am doing similar to what is there in Unity docs. I need to override the animation clips on fly (through script).