Monday 18 January 2016

Func Keyword in C# with lambda expression

Q: What is Func Keyword in C#?
Ans: We could say it is a type of parameterized delegate in C#.
in this given example i am going to describe how func keyword is working with lamda expression and how we can have body of a function with return type in generic Func.


using System;
 
namespace Func_Keyword
{
    class Program
    {
 
        public static string UpperName(string name)
        {
            return name.ToUpper();
        }
 
        static void Main(string[] args)
        {
 
 
            Func<stringfunc1 = () => "My name is Raj";
            Func<stringstringfunc2 = (solutation) => solutation + " Raj";
            Func<stringstringstringfunc3 = (solutationname) => solutation + " " + name;
 
            Console.WriteLine(func1.Invoke());
            Console.WriteLine(func2.Invoke("Mr."));
            Console.WriteLine(func3.Invoke("Mr.""Raj"));
 
 
            func2 = UpperName;
            Console.WriteLine(func2("i was in lowercase but now uppercase"));
            Console.WriteLine(func2.Invoke("i was in lowercase but now uppercase"));
 
 
            Func<stringfunc4 = () =>
            {
                return "Again i am Raj";
            };
            Console.WriteLine(func4());
 
            Console.ReadLine();
 
        }
 
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
 
namespace ActionFunc
{
    public static class Extension
    {
        public static List<stringAddPrefix(this List<stringvaluesstring prefixFunc<stringboolcondition = null)
        {
            if (condition == null)
            {
                return (from s in values
                        select prefix + " " + s).ToList();
            }
            else
            {
                return (from s in values
                        where condition(s)
                        select prefix + " " + s).ToList();
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var names = new List<string>() { "raj""Raja" };
            var prefixNamesWithCondition = names.AddPrefix("mr."name => name.Length > 3);
            var prefixNamesWithDefault = names.AddPrefix("mr.");
            Console.Read();
        }
    }
}


using System;
 
namespace CreateMethodWithFunc
{
    public static class StringExtension {
        public static string AddTabAsSufix(this string textint tabCountFunc<string,stringarrangeInput )
        {
            //string tab = string.Empty;
            //for (int i = 0; i < tabCount; i++)
            //{
            //    tab += "\t";
            //}
            //return arrangeInput(text + tab);
            return arrangeInput(text + string.Empty.PadLeft(tabCount'\t') );
 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("raj".AddTabAsSufix( 5 , s => s + "kumar"));
            Console.Read();
        }
    }
}

Callback example with Action in C#

using System;
 
namespace CallBackFunc
{
    public enum ValidationType
    {
        Email,
        HttpUrl,
        HttpsUrl
    }
    public class Validator
    {
 
        public static void Validate(ValidationType validationType, object data, Action onSuccess, Action<string> onFailoure)
        {
            ValidationResponse validationResponse;
            switch (validationType)
            {
                case ValidationType.Email:
                    validationResponse = IsValidEmail((string)data);
                    break;
                case ValidationType.HttpUrl:
                    validationResponse = IsValidHttpUrl((string)data);
                    break;
                case ValidationType.HttpsUrl:
                    validationResponse = IsValidHttpsUrl((string)data);
                    break;
                default:
                    validationResponse = new ValidationResponse { IsValid = false, Message = $"Invalid {validationType}" };
                    break;
            }
 
            if (validationResponse.IsValid)
            {
                onSuccess();
            }
            else
            {
                onFailoure(validationResponse.Message);
            }
        }
 
 
        private static ValidationResponse IsValidEmail(string email)
        {
            return new ValidationResponse { IsValid = false, Message = "Invalid email." };
        }
        private static ValidationResponse IsValidHttpUrl(string httpUrl)
        {
            return new ValidationResponse { IsValid = false, Message = "Invalid httpUrl." };
        }
        private static ValidationResponse IsValidHttpsUrl(string httpsUrl)
        {
            return new ValidationResponse { IsValid = httpsUrl.Contains("valid"), Message = "Invalid httpsUrl." };
        }
 
    }
 
    class ValidationResponse
    {
        public bool IsValid { getset; }
        public string Message { getset; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
             
            Validator.Validate(ValidationType.HttpsUrl, "http://aaavalid.com",
                onSuccess: () =>
                {
                    Console.WriteLine($"Wooh! I am valid {ValidationType.HttpsUrl}.");
                },
                onFailoure: (message) =>
                {
                    Console.WriteLine(message);
                });
 
            Console.ReadLine();
        }
    }
}

Action<T>
The Generic Action<> delegate is defined in the System namespace of microlib.dll
This Action<> generic delegate, points to a method that takes up to 16 Parameters and returns void.

Func<T>
The generic Func<> delegate is used when we want to point to a method that returns a value.
This delegate can point to a method that takes up to 16 Parameters and returns a value.
Always remember that the final parameter of Func<> is always the return value of the method. (For examle Func< int, int, string>, this version of the Func<> delegate will take 2 int parameters and returns a string value.)