The Grayzone

Action Delegate

I recently wrote a small application for transferring files which searches through the specified folder and any child folders for files matching the specified filter. The application has a checkbox for the user to select whether to copy or cut/move the file.

I decided to use the Action delegate to set the action to perform when transferring the file, either FileInfo.CopyTo() or FileInfo.MoveTo().

The Action delegate encapsulates a method that takes in up to 4 parameters and returns void.

First I declare the Action delegate, using the Action<T, T1> constructor, specifying that it is a delegate that takes a string and a FileInfo object.

using System.IO;
using System;

private Action<string, FileInfo> transferFile;
I then have an event handler for the Transfer button on the form, which kicks off the transfer process. Firstly I need to check if the user wants to copy or cut the files and give the transferFile delegate a value by using an anonymous method.

if (cbMove.Checked)
{
    transferFile = (destFileName, file) =>
    {
        file.MoveTo(destFileName);
    };
}
else
{
    transferFile = (destFileName, file) =>
    {
        file.CopyTo(destFileName);
    };
}

transferFile can now be called later in my code by calling it like a standard method, which then calls CopyTo() or MoveTo() depending on the anonymous function assigned earlier.

transferFile(destFile, file);

The Action delegate is also handy as it is used by the Array.ForEach method. The signature of Array.ForEach is:

public static void ForEach<T>(T[] array, Action<T> action) I use the following code to get a list of all files to be moved/copied using:

DirectoryInfo di = new DirectoryInfo("C:\\Test");
var files = di.GetFiles("*.css", SearchOption.AllDirectories);
Array.ForEach(files, copyFiles);

where copyFiles is a standard method that takes in a FileInfo object as this matches the required Action delegate signature.

private void copyFiles(FileInfo file)
{ 
    //copy all files 
}

Similar to the Action delegate are the Predicate which returns bool and Func which takes up to 4 parameters and returns a value of a specified type.

I’ll upload the wee app soon if anyone fancies a look!


Share this: