C# Fundamentals - Funcs & Actions


C# Fundamentals - Funcs & Actions

Before continuing on Actions & Funcs, you should have an understanding of delegates in C#.
A tutorial on delegates can be found HERE.
This is going to be a short and sweet run down of what they are.

Actions

Actions are delegates which have a return type of void. The parameters of an Action is set by using the type parameters.
Syntax:
[<modifiers>] Action<[Param1 type],[Param2 type],..[ParamN type]> <Name>
Eg:
using System;
namespace BitShiftProductions
{    
    public class Program
    {
        public Action<string, int> ActionDelegate;

        public static void CallMethod(string text, int digit)
        {
            Console.WriteLine ("Called Method with action : {0} {1}", text, digit);
        }
    
        public static void Main(string[] args)
        {
            Program p = new Program();
            p.ActionDelegate = CallMethod;
            p.ActionDelegate.Invoke("Hello", 44);
        }
    }
}
Output:
Called Method with action : Hello 44

Funcs

Func delegates closely resemble Actions but Funcs can not return void. They have to return a value, so it will always require a type argument to specify what the return type is, and the return type will be the type parameter specified last. The others are the function parameters.
Syntax:
[<modifiers>] Func<[Param1 type],[Param2 type],..[Return type]> <Name>
Eg:
using System;
namespace BitShiftProductions
{    
    public class Program
    {
        public Func<string, int> FuncDelegate;

        public static int CallMethod(string text)
        {
            Console.WriteLine ("Called Method with Func : " + text);
            return 44;
        }
    
        public static void Main(string[] args)
        {
            Program p = new Program();
            p.FuncDelegate = CallMethod;
            int x = p.FuncDelegate.Invoke("Hello");
            Console.WriteLine("Returned : " + x);
        }
    }
}
Output:
Called Method with Func : Hello
Returned : 44
Support Bitshift Programmer by leaving a like on Bitshift Programmer Facebook Page and be updated as soon as there is a new blog post.
If you have any questions that you might have about shaders or unity development in general don't be shy and leave a message on my facebook page or down in the comments.
For More C# Tutorials, go HERE.