.Net using Func<> and Action<>

An example of how to use Func<> and Action<>.

using System;
using System.Collections.Generic;
using System.Linq;

namespace FuncAndActionDemo
{
    /// <summary>
    /// Class to test Func and Action
    /// </summary>
    public static class FuncAndActionDemo
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        static void Main(string[] args)
        {
            const string name = "Test name";

            for (var i = 0; i < 10; i++)
            {
                var result = IsValid(new TestClass(string.Concat(name,i.ToString())));
                Action<String> print = PrintResults;
                new List<String> { result.ToString() }.ForEach(print);
            }
  
            Console.ReadKey();
        }

        private static void PrintResults(string results)
        {
            Console.WriteLine(results);
        }

        /// <summary>
        /// Determines whether the specified test is valid.
        /// </summary>
        /// <param name="test">The test.</param>
        /// <returns></returns>
        private static bool IsValid(TestClass test)
        {
            // Declare a func
            Func<TestClass, bool>[] rules =
                {
                    m => bool.Parse(m.IsTrue.ToString()),
                    m => !bool.Parse(m.IsFalse.ToString()),
                    m => !string.IsNullOrEmpty(m.HasName)
                };

            return rules.All(rule => rule(test));
        }
    }

    /// <summary>
    /// Class to demonstrate rule testing
    /// </summary>
    public class TestClass
    {

        public bool IsTrue { get; set; }
        public bool IsFalse { get; set; }
        public string HasName { get; set; }

        private readonly string _name;

        /// <summary>
        /// Initializes a new instance of the <see cref="TestClass"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        public TestClass(string name)
        {
            _name = name;
            IsOn();
            IsOff();
            CheckHasName(_name);
        }

        /// <summary>
        /// Determines whether this instance is on.
        /// </summary>
        private void IsOn()
        {

            IsTrue = true;
        }

        /// <summary>
        /// Determines whether this instance is off.
        /// </summary>
        private void IsOff()
        {
            IsFalse = false;

        }

        /// <summary>
        /// Checks the name of the has.
        /// </summary>
        /// <param name="name">The name.</param>
        private void CheckHasName(string name)
        {
            HasName = name;
        }
    }
}

Leave a Reply

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