Classes and Functions

Introduction

We have already learned how to create an object by declaring a variable of a class type. Here is an example:

using static System.Console;

Square sqr = new(248.57);
    
WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");
    
public class Square(double side)
{
    public double Side
    {
        get { return side; }
    }
    
    public double CalculatePerimeter()
    {
        return side * 4;
    }
    
    public double CalculateArea()
    {
        return side * side;
    }
}

This would produce:

Square Characteristics
----------------------------
Side:      248.57
Perimeter: 994.28
Area:      61787.04489999999
============================
    
Press any key to close this window . . .

As mentioned in our introduction to classes, when you declare a variable using the new operator, you are said to get a reference to the memory area where the object will be located.

Practical LearningPractical Learning: Introducing Parameters

  1. Start Microsoft Visual Studio
  2. Create a new Console App named PayrollPreparation4
  3. In the Solution Explorer, right-click PayrollPreparation4 -> Add -> New Folder
  4. Type Models as the name of the new folder
  5. In the Solution Explorer, right-click the new Models folder -> Add -> Class...
  6. Type Employee as the name of the new class/file
  7. Click Add
  8. Change the class as follows:
    namespace PayrollPreparation4.Models
    {
        internal class Employee
        {
            internal required int    EmployeeNumber { get; set; }
            internal required string FirstName      { get; set; }
            internal required string LastName       { get; set; }
            internal required double HourlySalary   { get; set; }
        }
    }
  9. In the Solution Explorer, right-click the Model folder -> Add -> Class...
  10. Type TimeSheet as the name of the new class/file
  11. Click Add
  12. Change the class as follows:
    namespace PayrollPreparation40.Models
    {
        internal class TimeSheet
        {
            private int tsNbr;
            private int empl;
            private double salary;
            private double result;
    
            private double mon, tue, wed, thu, fri;
    
            internal TimeSheet(int ts, int emplNbr, double m, double t, double w, double h, double f)
            {
                tsNbr = ts;
                empl = emplNbr;
                mon = m;
                tue = t;
                wed = w;
                thu = h;
                fri = f;
            }
    
            internal int GetTimeSheetNumber()
            {
                return tsNbr;
            }
    
            internal int GetEmployeeNumber()
            {
                return empl;
            }
    
            internal double GetMondayWork()
            {
                return mon;
            }
    
            internal double GetTuesdayWork()
            {
                return tue;
            }
    
            internal double GetWednesdayWork()
            {
                return wed;
            }
    
            internal double GetThursdayWork()
            {
                return thu;
            }
    
            internal double GetFridayWork()
            {
                return fri;
            }
    
            private double GetSalary()
            {
                salary = 0.00;
    
                if (empl == 370_595)
                {
                    salary = 28.25;
                }
                else if (empl == 826_384)
                {
                    salary = 24.37;
                }
                else if (empl == 175_004)
                {
                    salary = 26.97;
                }
                else if (empl == 697_415)
                {
                    salary = 31.57;
                }
                else
                    salary = 0.00;
    
                return salary;
            }
    
            internal double CalculateTimeWorked()
            {
                return mon + tue + wed + thu + fri;
            }
    
            internal double CalculateRegularTime(double time)
            {
                result = time;
    
                if (time is > 40.00)
                {
                    result = 40.00;
                }
    
                return result;
            }
    
            internal double CalculateRegularPay(double time)
            {
                result = GetSalary() * time;
    
                if (time is > 40.00)
                {
                    result = GetSalary() * 40.00;
                }
    
                return result;
            }
    
            internal double CalculateOvertime(double time)
            {
                result = 0.00;
    
                if (time is > 40.00)
                {
                    result = time - 40.00;
                }
    
                return result;
            }
    
            internal double CalculateOvertimePay(double time)
            {
                result = 0.00;
    
                if (time is > 40.00)
                {
                    result = salary * 1.50 * time;
                }
    
                return result;
            }
    
            internal double CalculateGrossPay(double time)
            {
                return CalculateRegularPay(time) + CalculateOvertimePay(time);
            }
        }
    }

Producing an Object

You can create a function that returns an object. To start, when creating the function, specify its return type as the desired class. In the body of the function, you can do anything you want. Before the closing curly bracket of the function, you must return an object of the class indicated as the returned type.

ApplicationPractical Learning: Producing Objects

  1. In the Solution Explorer, right-click Program.cs and click Rename
  2. Type PayrollProcessing (to get PayrollProcessing.cs)
  3. Above the Code Editor, click the PayrollProcessing.cs tab and change the document as follows:
    using static System.Console;
    using PayrollPreparation4.Models;
    
    PreparePayroll();
    
    Employee Hire(int number)
    {
        Employee empl1 = new Employee()
        {
            EmployeeNumber = 370_595,
            FirstName      = "Michael",
            LastName       = "Carlock",
            HourlySalary   = 28.25
        };
        Employee empl2 = new Employee()
        {
            EmployeeNumber = 826_384,
            FirstName      = "Catherine",
            LastName       = "Busbey",
            HourlySalary   = 24.37
        };
        Employee empl3 = new Employee()
        {
            EmployeeNumber = 175_004,
            FirstName      = "Andrew",
            LastName       = "Sanders",
            HourlySalary   = 26.97
        };
        Employee empl4 = new Employee()
        {
            EmployeeNumber = 697_415,
            FirstName      = "Jennifer",
            LastName       = "Simms",
            HourlySalary   = 31.57
        };
    
        if (number == 370_595)
        {
            return empl1;
        }
        else if (number == 826_384)
        {
            return empl2;
        }
        else if (number == 175_004)
        {
            return empl3;
        }
        else if (number == 697_415)
        {
            return empl4;
        }
    
        return new Employee() { EmployeeNumber = 0, FirstName = "John", 
                                LastName = "Doe", HourlySalary = 0.00 };
    }
    
    TimeSheet GetTimeWorked(int number)
    {
        TimeSheet ts1 = new TimeSheet(100_000, 370_595, 7,    8,    6.5, 8.5, 6.5);
        TimeSheet ts2 = new TimeSheet(205_000, 826_384, 9.5,  8,   10.5, 9,   8.5);
        TimeSheet ts3 = new TimeSheet(505_500, 175_004, 9,   10.5,  7,   9.5, 8.5);
        TimeSheet ts4 = new TimeSheet(202_240, 697_415, 8,    8,    8,   8,   8  );
    
        if (number == 205_000)
        {
            return ts2;
        }
        else if (number == 202_240)
        {
            return ts4;
        }
        else if (number == 505_500)
        {
            return ts3;
        }
        else if (number == 100_000)
        {
            return ts1;
        }
    
        return new TimeSheet(0, 0, 0, 0, 0, 0, 0);
    }
    
    void PreparePayroll()
    {
        int nbr = 100_000;
    
        TimeSheet timeSheet = GetTimeWorked(nbr);
        Employee  staff     = Hire(timeSheet.GetEmployeeNumber());
    
        double timeWorked   = timeSheet.CalculateTimeWorked();
    
        WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Evaluation");
        WriteLine("=======================================================");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
        WriteLine("Employee #:      {0}", timeSheet.GetEmployeeNumber());
        WriteLine($"Full Name:       {staff.FirstName} {staff.LastName}");
        WriteLine($"Hourly Salary:   {staff.HourlySalary:f}");
        WriteLine("=======================================================");
        WriteLine("Time Worked Summary");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
        WriteLine("--------+---------+-----------+----------+-------------");
        Write($"  {timeSheet.GetMondayWork():f}  |   ");
        Write($"{timeSheet.GetTuesdayWork():f}  |    ");
        Write($"{timeSheet.GetWednesdayWork():f}   |   ");
        Write($"{timeSheet.GetThursdayWork():f}   |  ");
        WriteLine($"{timeSheet.GetFridayWork():f}");
        WriteLine("========+=========+===========+==========+=============");
        WriteLine("                                    Pay Summary");
        WriteLine("-------------------------------------------------------");
        WriteLine("                                   Time   Pay");
        WriteLine("-------------------------------------------------------");
        WriteLine("                     Regular:    {0:f}   {1:f}",
                timeSheet.CalculateRegularTime(timeWorked),
                timeSheet.CalculateRegularPay(timeWorked));
        WriteLine("-------------------------------------------------------");
        WriteLine("                     Overtime:    {0:f}   {1:f}",
                timeSheet.CalculateOvertime(timeWorked),
                timeSheet.CalculateOvertimePay(timeWorked));
        WriteLine("=======================================================");
        WriteLine("                     Net Pay:            {0:f}",
                timeSheet.CalculateGrossPay(timeWorked));
        WriteLine("=======================================================");
    }
  4. To execute, on the main menu, click Debug -> Start Without Debugging:
    +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Employee #:      370595
    Full Name:       Michael Carlock
    Hourly Salary:   28.25
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      7.00  |   8.00  |    6.50   |   8.50   |  6.50
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    36.50   1031.12
    -------------------------------------------------------
                         Overtime:    0.00   0.00
    =======================================================
                         Net Pay:            1031.12
    =======================================================
    
    Press any key to close this window . . .
  5. Return to your programming environment

Passing an Object as Argument

A Class Type as a Parameter

An object of a class can be passed as argument. When creating a function, simply provide the name of a class as type followed by a name for the parameter. You can use a class from the .NET Framework or your own class. In the body of the function, you can ignore or use the parameter as you want. When it comes to a class used as a parameter, its public and internal members are available to the function that uses it. When calling the function, you must provide an object created from the class. Here is an example:

using static System.Console;

Square sqr = new(2938.748);

Display(sqr);

void Display(Square square)
{
    WriteLine("Square Characteristics:");
    WriteLine("-------------------------");
    WriteLine($"Side:      {square.Side}");
    WriteLine($"Perimeter: {square.Perimeter()}");
    WriteLine($"Area:      {square.Area()}");
    WriteLine("=========================");
}

public class Square
{
    public double Side { get; set; }

    public Square(double sideLength)
    {
        Side = sideLength;
    }

    public double Perimeter()
    {
        return Side * 4.00;
    }

    public double Area()
    {
        return Side * Side;
    }
}

This would produce:

Square Characteristics:
-------------------------
Side:      2938.748
Perimeter: 11754.992
Area:      8636239.807504
=========================

Press any key to close this window . . .

Passing an Object IN

We already know that, when you pass an argument to a method, if the method will not change the value(s) of the object, you should pass the argument as an IN parameter. This is also possible with objects passed to a method. Therefore, if a method will not modify a parameter, precede the data type of the parameter with the in keyword. Here is an example:

using Chemistry3.Models;
using static System.Console;

void Present(in Element obj)
{
    WriteLine("Chemistry");
    WriteLine("------------------------");
    WriteLine("Symbol:        " + obj.Symbol);
    WriteLine($"Atomic Number: {obj.AtomicNumber}");
    WriteLine("Element Name:  " + obj.ElementName);
    WriteLine($"Atomic Weight: " + obj.AtomicWeight);
    Write("========================");
}

Passing an Object by Reference

You can create a function or method that uses a parameter of a class type and the argument can be passed by reference. To do this, when creating the function or method, in its parentheses, precede the class name of the parameter with the ref keyword. When calling the function or method, precede the argument with the ref keyword. As seen with primitive types, if you pass a parameter by reference, if the function or method modifies the argument, this causes it to produce an object with a new version.

Passing an Object Out

As mentioned already, another way to pass an argument by reference is by using the out keyword. The concept also applies to objects passed as arguments.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2011-2026, FunctionX Sunday 21 January 2024 Next