pass a method as a parameter

Y

yoramo

hello

can I pass a static method as a parameter to a method?

if the answer is yes how do I do that ? how do I call the method ?

yoramo.
 
M

Morten Wennevik

hello

can I pass a static method as a parameter to a method?

if the answer is yes how do I do that ? how do I call the method ?

yoramo.

Is this what you mean?

private static string name = "Hello World!";

private static string method1()
{
return name;
}

private void method2(string text)
{
MessageBox.Show(text);
}

private void method3()
{
method2(method1());
}
 
Y

yoramo

No. I need a way to call a method that will be pass as a parameter to
another method.

hello

can I pass a static method as a parameter to a method?

if the answer is yes how do I do that ? how do I call the method ?

yoramo.

Is this what you mean?

private static string name = "Hello World!";

private static string method1()
{
return name;
}

private void method2(string text)
{
MessageBox.Show(text);
}

private void method3()
{
method2(method1());
}
 
S

Shiv Kumar

You need to use Delegates for this. A Delegate is strongly typed method pointer.

You define a delegate like so:

public delegate void DoSomethingDelegate(int i);

(This is a kind of global delegate. You could define a delegate within a class as well).
Delegates are objects (even thou the decleration above might not indicate as such) and so need to be created before you can use them. They typically take a parameter in their constructor, a method that has the same signature as the delegate.

So lets say you have a method called Calcuate in a class that has the same signature as the delegate above and you wanted to pass this method to another object (or method) you would do this

private void Calculate(int num)
{
//Some code here
}

TheMethodThatRequiresAMethodAsAParamter(new DoSomethingDelegate(Calculate));



public void TheMethodThatRequiresAMethodAsAParamter(DoSomethingDelegate m)
{

}

Now the parameter m is your reference to the meothd Calculate so you can call calculate simply like so:

m(56);

FYI, you can pass static and even private methods as parameters to a delegate's contructor. You can even have a return type in a delegate instead of void (I won't go into multicast delegates here to keep things simply).


Hope this helps.
 

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