Type cast to a target type from just its string representation

S

Sathyaish

sTypeName = ... //do some string stuff here to get the name of the
type

/*
The Assembly.CreateInstance function returns a type
of System.object. I want to type cast it to
the type whose name is sTypeName.

assembly.CreateInstance(sTypeName)

So, in effect I want to do something like:

*/

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);

How do I do that? And, what do I take on the left side of the
assignment expression, assuming this is C# 2.0. I don't have the var
keyword.
 
A

Alberto Poblacion

Sathyaish said:
So, in effect I want to do something like:

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);

No, this doesn't make sense. What would you assign it to? The only
reason why you would perform the cast is to assign the result to a variable
of that precise type:

TheType variable = assembly.CreateInstance(sTypeName) as
Type.GetType(sTypeName);

But if you already know TheType at compile time, then you can simply
cast to that type:

TheType variable = assembly.CreateInstance(sTypeName) as TheType;

And if you don't know the type at compile time, you can only declare
the variable as object, so you don't need any cast:

object variable = assembly.CreateInstance(sTypeName);
 
J

Jeff Johnson

sTypeName = ... //do some string stuff here to get the name of the
type

/*
The Assembly.CreateInstance function returns a type
of System.object. I want to type cast it to
the type whose name is sTypeName.

assembly.CreateInstance(sTypeName)

So, in effect I want to do something like:

*/

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);

How do I do that? And, what do I take on the left side of the
assignment expression, assuming this is C# 2.0. I don't have the var
keyword.

Generally the only time that this sort of run-time instantiation is of any
use is when the object you're creating is either a sub-class of a known
class or implements a particular interface. If you just want a concrete
object of a specific class, then you ALREADY KNOW you want an object of a
specific class and there's no need for this dynamic object creation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top