C# Create object from a value in a string variable

129 Views Asked by At

I want to get the type of the value stored in the 'result' variable. Assume I dont know the 'result' value and the value comes during runtime.

string result="System.IO.Directory";

MetadataReference[] references =
{
    MetadataReference.CreateFromFile(path: typeof(result).Assembly.Location)
}

Is there any way to do this?

1

There are 1 best solutions below

3
Athanasios Kataras On

Would the following statement work for your? The string below should be in a format like this "FullyQualifiedName, AssembleName"

Type type = Type.GetType("System.IO.Directory, System.IO.FileSystem");
MetadataReference[] references =
{
    MetadataReference.CreateFromFile(path: 
     type.Assembly.Location)
 }

The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

Word to the wise, these solutions always require some type of reflection, and while it is a tool as good as any, too much of it can cause performance issues.