Exploring Ruby’s ‘times()’ Function in C#/Unity

Introduction

In the world of programming, different languages often have their own unique features and functions that make them stand out. Ruby, a dynamically-typed scripting language known for its simplicity and elegance, has a handy function called ‘times()’ that allows you to execute a block of code a specified number of times. But what if you’re working in C#, particularly in the context of Unity game development? Is there a way to achieve the same functionality? In this blog, we’ll explore how you can replicate Ruby’s ‘times()’ function in C#/Unity.

I’ve seen a lot of people enthuse about Ruby’s times() function which allows you to write code like:

5.times { |i| puts i }

The syntax is genuinely elegant, and it occurred to me that a similar approach could be applied in C# by defining the following extension method for integers:

public static class IntExtensions
{
    public static void Times(this int i, Action<int> func)
    {
        for(int j = 0; j < i; j++)
        {
            func(j);
        }
    }
}

Which then lets you write:

5.Times(i => Console.Write(i));

However, if you run this in a Unity project with the default imports the following error occurs:

error CS0246: The type or namespace name Action could not be found. Are you missing a using directive or an assembly reference?

The Solution

using System;

As the Action is part of the System namespace, makes sure that the Action delegate type is properly imported from the System namespace by adding using System; as a directive at the top of your C# file. This directive is necessary for the code to compile successfully.

Happy looping!