I have a C# program, how can I check at runtime if a namespace, class, or method exists? Also, how to instantiate a class by using it's name in the form of string?
Pseudocode:
string @namespace = "MyNameSpace";
string @class = "MyClass";
string method= "MyMEthod";
var y = IsNamespaceExists(namespace);
var x = IsClassExists(@class)? new @class : null; //Check if exists, instantiate if so.
var z = x.IsMethodExists(method);
You can use Type.GetType(string) to reflect a class. Type
has methods to discover other members, including a method, that are available to that type.
One trick, however, is that GetType
wants an assembly-qualified name. If you use just the class name itself, it will assume you are referencing the current assembly.
So, if you wanted to find the type in all loaded assemblies, you can do something like this (using LINQ):
var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Name == className
select type);
Of course, there may be more to it than that, where you'll want to reflect over referenced assemblies that may not be loaded yet, etc.
As for determining the namespaces, reflection doesn't export those distinctly. Instead, you'd have to do something like:
var namespaceFound = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Namespace == namespace
select type).Any()
Putting it all together, you'd have something like:
var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Name == className && type.GetMethods().Any(m => m.Name == methodName)
select type).FirstOrDefault();
if (type == null) throw new InvalidOperationException("Valid type not found.");
object instance = Activator.CreateInstance(type);
You can resolve a Type from a string by using the Type.GetType(String) method.
For example:
Type myType = Type.GetType("MyNamespace.MyClass");
You can then use this Type instance to check if a method exists on the type by calling the GetMethod(String) method.
For example:
MethodInfo myMethod = myType.GetMethod("MyMethod");
Both GetType and GetMethod return null
if no type or method was found for the given name, so you can check if your type/method exist by checking if your method call returned null or not.
Finally, you can instantiate your type using Activator.CreateInstance(Type)
For example:
object instance = Activator.CreateInstance(myType);
One word: Reflection. Except for Namespaces, you'll have to parse those out of the Type names.
EDIT: Strike that - for namespaces you'll have to use the Type.Namespace property to determine which namespace each class belongs to. (See HackedByChinese response for more information).