DEV Community

Bruce Axtens
Bruce Axtens

Posted on

2 1

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.

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay