That simply isn't possible. The compiler is static typed (except for when it isn't ;p). t
is a variable. variable != static. What you want to do isn't possible.
One option here is generics, but that still gets it you as a <T>
, which doesn't help any if <T>
still only knows about the same methods as object
. Another option is dynamic
; that means inst.Foo();
will work - but only at runtime, and only if the type really does have a Foo()
method; importantly, the compiler still won't know about t
's methods at compile-time.
From the comments, it seems that the intended usage here is for method overload resolution; dynamic
can help with that - for example:
Foo(Customer cust) {...}
Foo(Order order) {...}
Foo(Region region) {...}
object inst = Activator.CreateInstance(t); // t probably one of the above types
...
Foo((dynamic)inst);
will try to invoke the most appropriate Foo
overload based on the runtime type of inst
, with per-type cache optimizations etc. It is a bit of a hack, but it works, and is easier and cleaner than checking manually (and thanks to the strategy cache, often more efficient too).
If the only thing you are doing with inst
is passing it onwards, you could make inst
itself dynamic
:
dynamic inst = Activator.CreateInstance(t);
Foo(inst);
Note that you should generally be a little cautious of this, however, as once a variable is dynamic
, all access to it is via the dynamic
API - even a call to a method that takes an object
parameter (such as string.Format
) would be routed via the runtime rather than the compiler (unless of course you explicitly cast it back to object
or similar).