DEV Community

Bruce Axtens
Bruce Axtens

Posted on

Func delegates in C#

Today I added another delegate to Lychen and will likely add it to other things in the near future. This one is the famous (?) glob which appears in all sorts of languages.

            v8.Script.glob = (Func<string, string[]>)Glob;
Enter fullscreen mode Exit fullscreen mode

Func<> is different to Action<> in that the last parameter inside the angle-brackets defines the return type. Action<> is for void returns. Func<> for everything else (except a third thing that I don't understand yet.)

Glob's implemented like this.

        private static string[] Glob(string wildcard)
        {
            var path = Path.GetDirectoryName(wildcard);
            if (path.Length == 0)
            {
                path = ".\\";
            }
            wildcard = Path.GetFileName(wildcard);
            return Directory.GetFiles(path, wildcard);
        }
Enter fullscreen mode Exit fullscreen mode

Note that the definition of the delegate must match the implementation. In this case the delegate is declared as having a string input and a string array output.

Glob uses System.IO.Path functions to split the incoming parameter into path and wildcard before giving both to Directory.GetFiles. Somewhere down the line I'm going to have to allow for the optional third parameter to GetFiles but for now this meets the need.

The other issue is that a non-native array is returned to Lychen. This means that .length doesn't work. Instead, you use .Length to get the number of items in the array. In fact, .map and .forEach etc don't work either. There is a fix for this also, but again, the motivation is lacking.

Discussion (0)