By using a dynamic variable, the variable is dynamic, not the object the variable is referring to. That is, there is no static type checking when you want to access members of the object or want to convert it. You need some other magic to be able to do that.
You could wrap your Foo in a DynamicObject where you can specify how the conversion takes place.
public class DynamicWrapper<T> : DynamicObject
{
public T Instance { get; private set; }
public DynamicWrapper(T instance)
{
this.Instance = instance;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.ReturnType == typeof(T))
{
result = Instance;
return true;
}
if (binder.ReturnType == typeof(T[]) && binder.Explicit)
{
result = new[] { Instance };
return true;
}
return base.TryConvert(binder, out result);
}
public override string ToString()
{
return Convert.ToString(Instance);
}
}
Then you could do this:
dynamic dobj = new DynamicWrapper<Foo>(someFoo);
Foo foo1 = dobj;
Foo foo2 = (Foo)dobj;
Foo[] arr1 = (Foo[])dobj;
// someFoo == foo1 == foo2 == arr1[0]
dynamic darr = new DynamicWrapper<Foo[]>(arr1);
Foo[] arr2 = darr;
Foo[] arr3 = (Foo[])darr;
// arr1 == arr2 == arr3
// someFoo == arr2[0] == arr3[0]