Invoking a Static Method in a Static Class

G

Guest

I want to invoke a static method of a static class using a TEXT variable
which has the namespace and class name which should be executed. I looked at
the "CreateInstance" method, but this looks like a way to create an instance
of a class, which is not what is needed. I attempted to use this method,
even though I'm pretty sure that it is not applicable here and it fails as
the "Type" variable is null after I use the following instruction:

string myNamespace = "Fred.Utilities";
string clsName = "MyClass.cs";
Type myType = Type.GetType(myNamespace + "." + clsName);

To create an instance of the object (assuming a no parameter constructor -
And again, Since this is a static class with no constructor, I know that it
is not applicable, but I do intend to use the same sort of set up to create a
class which is not a static class and I was wanting to confirm that this
would be appropriate in that instance).

object obj = Activator.CreateInstance(myType);

Would this be the appropriate set of instructions to use on an Instance class?
How would I provide the arguements to the constructor if they were required?
How should I go about this for a static class/method?

Thanks in advance for your assistance!

After those instructions are created, myType = null.


Type
 
R

Roman Wagner

If you have a type object for your static class you can do the
following.

Type myStaticClassType;
//...
Object[] myStaticMethodArguments;
//...

MethodInfo mystaticMethodInfo =
myStaticClassType.GetMethod(myStaticMethodName);
Object myStaticMethodResult = mystaticMethodInfo.Invoke(null,
myStaticMethodArguments);

// do something usefull with myStaticMethodResult
 
S

Samuel R. Neff

For a static method you don't need to create an instance at all. Use
reflection to get the MethodInfo for the target method and then call
Invoke, passing null as the object reference.

HTH,

Sam
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

|I want to invoke a static method of a static class using a TEXT variable
| which has the namespace and class name which should be executed. I looked
at
| the "CreateInstance" method, but this looks like a way to create an
instance
| of a class, which is not what is needed. I attempted to use this method,
| even though I'm pretty sure that it is not applicable here and it fails as
| the "Type" variable is null after I use the following instruction:

If the method is static you dont have to create an instance, if you get a
Type instance of your class you can do InvokeMethod passing null for the
instance parameter.
 

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