Home

Techniques of Passing Arguments

 

Passing an Argument by Value

When calling a methods that takes one or more arguments, we made sure we provided the necessary value. This is because an argument is always required and the calling method must provided a valid value when calling such a method.

Passing an Argument by Reference

Consider the following program:

using System;

public class Payroll
{
    static void Earnings(double ThisWeek, double Salary)
    {
	ThisWeek = 42.50;

	Console.WriteLine("\nIn the Earnings() function,");
	Console.Write("Weekly Hours    = ");
	Console.WriteLine(ThisWeek);
	Console.Write("Salary          = ");
	Console.WriteLine(Salary);
	Console.Write("Weekly Salary:  = ");
	Console.WriteLine(ThisWeek * Salary);
    }

    static int Main()
    {
	double Hours, Rate;
		
	Rate  = 15.58;
	Hours = 26.00;
	
	Console.WriteLine("In the Main() function,");
	Console.Write("\nWeekly Hours   = ");
	Console.Write(Hours);
	Console.Write("\nSalary         = ");
	Console.WriteLine(Rate); 
	Console.Write("Weekly Salary    = ");
	Console.WriteLine(Hours * Rate);

	Console.WriteLine("\nCalling the Earnings() function");
	
	Earnings(Hours, Rate);

	Console.Write("\nAfter calling the Earnings() function, ");
	Console.WriteLine("\nin the Main() function,");
	Console.Write("\nWeekly Hours   = ");
	Console.Write(Hours);
	Console.Write("\nSalary         = ");
	Console.WriteLine(Rate);
	Console.Write("Weekly Salary    = ");
	Console.WriteLine(Hours * Rate);

	Console.Write("\n");
	return 0;
    }
}

This would produce:

In the Main() function,

Weekly Hours   = 26
Salary         = 15.58
Weekly Salary  = 405.08

Calling the Earnings() function

In the Earnings() function,
Weekly Hours    = 42.5
Salary          = 15.58
Weekly Salary:  = 662.15

After calling the Earnings() function,
in the Main() function,

Weekly Hours   = 26
Salary         = 15.58
Weekly Salary  = 405.08

Press any key to continue

Notice that the weekly hours and salary values are the same before and after calling the Earnings() method. 

When you declare a variable in a program, the compiler reserves an amount of space for that variable. If you need to use that variable somewhere in your program, you call it and make use of its value. There are two major issues related to a variable: its value and its location in the memory. The location of a variable in memory is referred to as its address.

If you supply the argument using its name, the compiler only makes a copy of the argument’s value and gives it to the calling method. Although the calling method receives the argument’s value and can use it in any way, it cannot (permanently) alter it. C# allows a calling method to modify the value of a passed argument if you find it necessary. If you want the calling method to modify the value of a supplied argument and return the modified value, you should pass the argument using its reference.

To pass an argument as a reference, when defining and when calling the method, precede the argument's data type with the ref keyword. You can pass 0, one, or more arguments as reference in the program or pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you want the called method to modify the argument and permanently change its value.

Another option consists of passing an argument using the out keyword. Here is an example:

using System;

class Exercise
{
    static void Initializer(out double n)
    {
	n = 128.44;
    }

    public static int Main()
    {
	double Number = 15.25;

	Console.WriteLine("Number = {0}", Number);
  	return 0;
    }
}

If you pass an argument with out, any modification made on the argument would be kept when the method ends. When calling a method that takes an out argument, precede the argument with the out keyword. Here is an example:

using System;

class Exercise
{
    static void Initializer(out double n)
    {
	n = 128.44;
    }

    public static int Main()
    {
	double Number = 15.25;

	Console.WriteLine("Number = {0}", Number);
	Initializer(out Number);
	Console.WriteLine("Number = {0}", Number);
	return 0;
    }
}

This would produce:

Number = 15.25
Number = 128.44

Practical Learning Practical Learning: Passing Arguments By Reference

  1. To pass arguments by reference, change the Cylinder.cs file as follows:
     
    using System;
    
    namespace Geometry1
    {
        class Cylinder
        {
            public void GetRadius(ref double rad)
            {
                Console.Write("Radius: ");
                rad = double.Parse(Console.ReadLine());
            }
    
            public void GetHeight(out double h)
            {
                Console.Write("Height: ");
                h = double.Parse(Console.ReadLine());
            }
    
            public double CalculateBaseArea(double rad)
            {
                return rad * rad * Math.PI;
            }
    
            public double CalculateLateralArea(double rad, double hgt)
            {
                return 2 * Math.PI * rad * hgt;
            }
    
            public double CalculateTotalArea(double rad, double hgt)
            {
                return 2 * Math.PI * rad * (hgt + rad);
            }
    
            public double CalculateVolume(double rad, double hgt)
            {
                return Math.PI * rad * rad * hgt;
            }
    
            public void Process()
            {
                double Radius = 0.00;
                double Height = 0.00;
                double BaseArea;
                double LateralArea;
                double TotalArea;
                double Volume;
    
                Console.WriteLine("Enter the dimensions of the cylinder");
                GetRadius(ref Radius);
                GetHeight(out Height);
    
                BaseArea = CalculateBaseArea(Radius);
                LateralArea = CalculateLateralArea(Radius, Height);
                TotalArea = CalculateTotalArea(Radius, Height);
                Volume = CalculateVolume(Radius, Height);
    
                Console.WriteLine("\nCylinder Characteristics");
                Console.WriteLine("Radius:  {0}", Radius);
                Console.WriteLine("Height:  {0}", Height);
                Console.WriteLine("Base:    {0:F}", BaseArea);
                Console.WriteLine("Lateral: {0:F}", LateralArea);
                Console.WriteLine("Total:   {0:F}", TotalArea);
                Console.WriteLine("Volume:  {0:F}", Volume);
            }
        }
    }
  2. Execute the application to test it. Here is an example:
     
    Enter the dimensions of the cylinder
    Radius: 24.55
    Height: 20.85
    
    Cylinder Characteristics
    Radius:  24.55
    Height:  20.85
    Base:    1893.45
    Lateral: 3216.16
    Total:   7003.05
    Volume:  39478.34
  3. Close the DOS window

Method Overloading

A typical program involves a great deal of names that represent variables and methods of various kinds. The compiler does not allow two variables to have the same name in the same method. Although two methods should have unique names in the same program, a class can have different methods with the same name if you follow some rules. The ability to have various methods with the same name in the same program is referred to as method overloading. To perform overloading, the methods must have different numbers or different type(s) of arguments.

The moment of inertia is the ability of a beam to resist bending. It is calculated with regard to the cross section of the beam. Because it depends on the type of section of the beam, its calculation also depends on the type of section of the beam. In this exercise, we will review different formulas used to calculate the moment of inertia. Since this exercise is for demonstration purposes, you do not need to be a Science Engineering major to understand it.

 

Practical Learning Practical Learning: Overloading a Method

  1. Create a new Console Application named MomentOfInertia1
     
    The Moment Of Inertia
  2. Change the file as follows:
     
    using System;
    
    public class NewProject
    {
        // Rectangle
        static double MomentOfInertia(double b, double h)
        {
    	return b * h * h * h / 3;
        }
    
        static int Main()
        {
    	double Base, Height;
    	
    	Console.WriteLine("Enter the dimensions of the Rectangle");
    	Console.Write("Base:    "); 
    	Base = double.Parse(Console.ReadLine());
    	Console.Write("Height: ");
    	Height = double.Parse(Console.ReadLine());
    	
    	Console.WriteLine("\nMoment of inertia with regard to the X axis: ");
    	Console.WriteLine("I = {0}mm", MomentOfInertia(Base, Height));
    	
    	Console.WriteLine();
    	return 0;
        }
    }
  3. Execute the application. Here is an example of running the program:
     
    Enter the dimensions of the Rectangle
    Base:    2.44
    Height: 3.58
    
    Moment of inertia with regard to the X axis:
    I = 37.3179390933333mm
  4. Close the DOS window
  5. A circle, and thus a semi-circle, requires only a radius. Since the other version of the MomentOfInertia() function requires two arguments, we can overload it by providing only one argument, the radius.
    To overload the above MomentOfInertia() method, type the following in the file:
     
    The Moment of Inertia for a Circle
    using System;
    
    public class NewProject
    {
        // Rectangle
        static double MomentOfInertia(double b, double h)
        {
    	return b * h * h * h / 3;
        }
    
        // Semi-Circle
        static double MomentOfInertia(double R)
        {
    	const double PI = 3.14159;
    	
    	return R * R * R * R * PI/ 8;
        }
    
        static int Main()
        {
    	double Base, Height;
    	double Radius;
    	
    	Console.WriteLine("Enter the dimensions of the Rectangle");
       	Console.Write("Base:    "); 
    	Base = double.Parse(Console.ReadLine());
    	Console.Write("Height: ");
    	Height = double.Parse(Console.ReadLine());
    	
    	Console.WriteLine("\nMoment of inertia with regard to the X axis: ");
    	Console.WriteLine("I = {0}mm", MomentOfInertia(Base, Height));
    		
    	Console.Write("\nEnter the radius: ");
    	Radius = double.Parse(Console.ReadLine());
    	
    Console.WriteLine("Moment of inertia of a semi-circle with regard to the X axis: ");
    	Console.WriteLine("I = {0}mm", MomentOfInertia(Radius));
    
    	Console.WriteLine();
    	return 0;
        }
    }
  6. Execute the program. Here is an example:
     
    Enter the dimensions of the Rectangle
    Base:    4.25
    Height: 2.55
    
    Moment of inertia with regard to the X axis:
    I = 23.49028125mm
    
    Enter the radius: 5.35
    Moment of inertia of a semi-circle with regard to the X axis:
    I = 321.717471644992mm
  7. Close the DOS window
  8. Here are the formulas considered for a triangle:

    As you can see, the rectangle and the triangle are using the same dimension types. This means that we can provide only the same kinds of arguments, the base and the height, to calculate the moment of inertia. This also means that the compiler will not allow us to write two methods that have the same name, the same number of arguments, and the same types of arguments because that would violate the rule of function overloading.

    In order to overload the MomentOfInertia() function, we will add an argument that will never be used; this argument will serve only as a “witness” to set the difference between both versions of the function. This “witness” argument can be anything: an integer, a character, a string, a float, etc. For our example, we will make it a simple integer. To use the version applied to the triangle, we will provide this argument to overload the MomentOfInertia() function. When called with only two arguments, the rectangle version will apply.
     
    Change the file as follows:
     
    using System;
    
    public class NewProject
    {
        // Rectangle
        static double MomentOfInertia(double b, double h)
        {
    	return b * h * h * h / 3;
        }
    
        // Semi-Circle
        static double MomentOfInertia(double R)
        {
    	const double PI = 3.14159;
    	
    	return R * R * R * R * PI/ 8;
        }
    	
        // Triangle
        static double MomentOfInertia(double b, double h, int i)
        {
    	return b * h * h * h / 12;
        }
    
        static int Main()
        {
    	double Base = 7.74, Height = 14.38, Radius = 12.42;
    		
    	Console.WriteLine("Rectangle - Moment of inertia with regard to the X axis: ");
    	Console.WriteLine("I = {0}mm", MomentOfInertia(Base, Height));
    	
    Console.WriteLine("\nSemi-Circle - Moment of inertia of a semi-circle with regard to the X axis: ");
    	Console.WriteLine("I = {0}mm", MomentOfInertia(Radius));
    		
    	Console.WriteLine("\nEnter the dimensions of the triangle");
    	Console.Write("Base:   ");
    	Base = double.Parse(Console.ReadLine());
    	Console.Write("Height: ");
    	Height = double.Parse(Console.ReadLine());
    
    	Console.WriteLine("\nTriangle - Moment of inertia with regard to the X axis: ");
    	Console.WriteLine("I = {0}mm", MomentOfInertia(Base, Height, 1));
    
    	Console.WriteLine();
    	return 0;
        }
    }

  9. Execute the program. Here is an example:
     
    Rectangle - Moment of inertia with regard to the X axis:
    I = 7671.78395376mm
    
    Semi-Circle - Moment of inertia of a semi-circle with regard to the X axis:
    I = 9344.28126291881mm
    
    Enter the dimensions of the triangle
    Base:   5.52
    Height: 3.84
    
    Triangle - Moment of inertia with regard to the X axis:
    I = 26.04662784mm
  10. Close the DOS window

Previous Copyright © 2006-2007 FunctionX, Inc. Next