With Type.GetType(string typeName)
and Activator.CreateInstance(Type type)
you can achieve it:
string className = "MiProyecto.Modelos.Persona";
Type classType = Type.GetType(className);
Persona persona = (Persona)Activator.CreateInstance(classType);
persona.Nombre = "Einer";
Here is a step by step.
First we save the name of the complete class with everything and namespace:
namespace MiProyecto.Modelos
{
public class Persona
{
public int Id { get; set;}
public string Nombre { get; set;}
}
}
Then in the variable we would have:
string className = "MiProyecto.Modelos.Persona";
Now we need the System.Type
of the class to be able to initialize it and we get it with Type.GetType()
:
Type classType = Type.GetType(className);
As we already have the information of the class, we can initialize it with Activator.CreateInstance()
:
Persona persona = (Persona)Activator.CreateInstance(classType);
persona.Nombre = "Einer";