C# Func and Action types

The Func type provides a way to store anonymous methods. For the Func type, the first type parameters are the arguments to the methods, and the final type parameter is the return value.

Example.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void FuncTypeTest()
    {
        Func<string, bool> validator =
        word =>
        {
            var count = word.Length;
            return count > 4;
        };
        var isValid = validator("AjitGoel");
        Assert.IsTrue(isValid);
    }
}

Action type objects do not return a value. They are similar to a void method.
A Func type on the other hand returns a result.

Action<int> action1 = (int counter) => Console.WriteLine("Write {0}", counter);

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.