C # - How do you return a string based type

For example, I have a class called Clothing that inherits from the abstract Product class.

public class Clothing : Product
{
    public bool IsInSeason {get; set;}
    public string Material {get; set; }
    public Decimal IsFeatured { get; set; }
}

Edit: In a function, how could I pass the string β€œClothes” and have the type of the return class?

ReturnTypeOfClassBasedOffOfString(string class)
{
    // ... 
}
+3
source share
5 answers

Use Type.GetType (string)

Note that sometimes the class name will not be enough. Someday you will need to provide AssemblyQualifiedName

"If the type is in the current executable assembly or in Mscorlib.dll, just specify the type name corresponding to its namespace."

+5
source

Type.GetType , : ? , - . Clothing?

BTW: ReturnTypeOfClassBasedOffOfString(string class) . ReturnTypeOfClassBasedOffOfString(string classname), ReturnTypeOfClassBasedOffOfString(string @class).

+1
static Type ReturnTypeOfClassBasedOffOfString(string className)
{
  foreach (Assembly a in AppDomain.Current.GetAssemblies ())
  {
    foreach (Type t in a.GetTypes ())
    {
      if (t.Name == className) // Ignore namespace
        return t;
    }
  }

  return null;
} 
0
source

you can use

Type.GetType("MyApplication.Product", true)

for this purpose, but you must include a namespace (for example, "MyApplication").

0
source

if you want to get type:

Type.GetType

enough. If you want to create an instance using its string name, you should use

Activator.CreateInstance

Goodluck

0
source

All Articles