how to define a variable of a type that is in a string

  • Thread starter =?iso-8859-1?B?RulybmFz?=
  • Start date
?

=?iso-8859-1?B?RulybmFz?=

Hello all,

Imagine that I have this:

string myType = "FormProducts"; // FormProducts is the product's
form...

then, I'd like to create a variable of type "FormProducts" (or other
type that is in a string)... it would be like this:

FormProducts variableName;

Does anyone know how can I get this?
 
N

Nicholas Paldino [.NET/C# MVP]

Fernas,

You can use the static CreateInstance method on the Activator class to
take a Type instance (which you can get through a call to the static GetType
method on the Type class) and then create an instance of your class.

However, it will be returned as an object, which you have to cast to an
interface, or base class that you can use. If you already have a reference
to the library that contains the type, then you could cast to an instance of
that, but then that defeats the purpose of making the call to CreateInstance
(unless you want to access an object through remoting).

Or, you could use reflection to make calls on the object if you know the
method names and parameter types, but don't have an interface/base class to
cast to.
 

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