Passing a method as a parameter

H

hardieca

Hello,

I'm creating a toolbox of useful functions, and I've added a function
that recursively drills down through a file system searching for files.
I've created a number of variations of this function, and I imagine
I'll continue to have use for it.

What I would like to do is create a version that will take a method as
a parameter and invoke it as it traverses my file system path. Here is
some pseudo-code that will hopefully illustrate what I'm trying to do:

public class Toolbox{
public void (string startDirectory, Method myMethod) fileDriller{
foreach (string f in Directory.GetFiles(startDirectory){
myMethod(f);
}
foreach (string d in Directory.GetDirectories(startDirectory){
fileDriller(d, myMethod);
}
}
}

So let's say I wanted to determine the length of each filename in a
directory of interest and every subdirectory:

public void lengthOfFileName(string fileName){
Console.write(fileName.Length.toString());
}

static void Main(){
Toolbox tb = new Toolbox();
tb.fileDriller("C:\\somedir", lengthOfFileName);
}

I tried passing a MethodInfo object, but I'm running into issues
because, I believe, it's an abstract class. If anyone has any idea how
I would accomplish this, please let me know!

Regards,

Chris
 
D

Dustin Campbell

If the signature of your method is known, use a delegate:

public void delegate FileMethod(string fileName);

public void FileDriller(string startDirectory, FileMethod myMethod)
{
foreach (string f in Directory.GetFiles(startDirectory))
myMethod(f);

foreach (string d in Directory.GetDirectories(startDirectory))
FileDriller(d, myMethod);
}

Dustin Campbell
Developer Express Inc
 

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