Navigate to Post

Thursday, April 9, 2020

Learn C#~#5 Local Functions

C# feature called local functions, which allows local methods to be defined and called within a method. This wasn’t possible before c#7. 

Local functions make the intent of your code clear. Anyone reading your code can see that the method is not callable except by the containing method. For team projects, they also make it impossible for another developer to mistakenly call the method directly from elsewhere in the class or struct. 

The following code snippet defines a method named "GetRate" & "GetDeduction" inside the "CalculateSalary" method.

PROGRAM


using System;

namespace MyTestConsole
{
    class Program
    {
        static void Main()
        {
            int employeeId = 10027;
            int workingDays = 22;

            var Result = CalculateSalary(employeeId, workingDays, EmployeeType.FullTime);
            Console.WriteLine($"Salary of employee-{employeeId} is {Result}");
            Console.ReadKey();
        }

        public enum EmployeeType
        {
            Contract, FullTime, PartTime
        }

        public static double CalculateSalary(int employeeId, int workingDays, EmployeeType employeeType)
        {
            double rate = GetRate(employeeType);
            double deductionAmount = GetDeduction(employeeId);

            return (rate * workingDays) - deductionAmount;

            //Local functions
            double GetRate(EmployeeType empType)
            {
                double rate = 0;
                switch (empType)
                {
                    case EmployeeType.Contract:
                        rate = 2000.0;
                        break;
                    case EmployeeType.FullTime:
                        rate = 3000.0;
                        break;
                    case EmployeeType.PartTime:
                        rate = 1500.0;
                        break;
                    default:
                        break;
                }
                return rate;
            }

            double GetDeduction(int employeeId)
            {
                //return standard deduction 1200 (assumption)
                return 1200.0;
            }
        }
    }
}

OUTPUT


All time trending post