Home

Methods and their Parameters

 

Arguments

 

Overview of an Argument

As we saw in the previous lesson, a method performs an assignment that completes the operations of a class. The methods we used in the previous lesson relied on global variables to exchange information with other sections of the program. Sometimes, a method would need one or more values in order to carry its assignment. The particularity of such a value or such values is that another method that calls this one must supply the needed values. When a method needs a value to complete its assignment, such a value is called an argument.

Practical Learning Practical Learning: Introducing Arguments

  1. Start Notepad and type the following:
     
    package Cylinder;
    import System.*;
    
    public class Exercise
    {
    	static double GetTheRadius()
    	{
    		double rad;
    
    		do 
    		{
    			Console.Write("Radius: ");
    			rad = Double.parseDouble(Console.ReadLine());
    			if( rad < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( rad < 0 );
    		return rad;
    	}
    
    	static double GetTheHeight()
    	{
    		double h;
    
    		do 
    		{
    			Console.Write("Height: ");
    			h = Double.parseDouble(Console.ReadLine());
    			if( h < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( h < 0 );
    
    		return h;
    	}
    
    	static void ProcessCylinder()
    	{
    		double radius;
    		double height;
    
    		Console.WriteLine("Enter the dimensions of the cylinder");
    		radius = GetTheRadius();
    		height = GetTheHeight();
    	
    		Console.WriteLine("\nCylinder Characteristics");
    		Console.WriteLine("Radius:  {0}", (System.Double)radius);
    		Console.WriteLine("Height:  {0}", (System.Double)height);
    	}
    	public static void main(String[] args)
    	{
    		ProcessCylinder();
    	}
    }
  2. Save the file in a new folder named Cylinder2 inside your JSharp Lessons folder
  3. Save the file as Exercise.jsl in the GCS1 folder
  4. Open the Command Prompt and switch to the JSharp Lessons\Cylinder2 folder
  5. To compile the application, type vjc Exercise.jsl and press Enter
  6. To execute the application, type Exercise and press Enter. Here is an example:
     
    Enter the dimensions of the cylinder
    Radius: 42.38
    Height: 22.48
    
    Cylinder Characteristics
    Radius:  42.38
    Height:  22.48
  7. Return to Notepad

Introduction to Arguments

Like a variable, an argument is represented by its type of value. For example, one method may need a character while another would need a string. Yet another method may require a decimal number. This means that the method or class that calls a method is responsible for supplying the right value, even though a method may have an internal mechanism of checking the validity of such a value.

The value supplied to a method is typed in the parentheses of the method and it's called an argument. In order to declare a method that takes an argument, you must specify its name and the argument between its parentheses. Because a method must specify the type of value it would need, the argument is represented by its data type and a name. If the method would not return a value, it can be declared as void.

Suppose you want to define a method that displays the side length of a square. Since you would have to supply the length, you can define such a method as follows:

using System;

public class NewProject
{
	void DisplaySide(double Length)
	{
	}
	static void Main()
	{
	}
}

In the body of the method, you may or may not use the value of the argument. Otherwise, you can manipulate the supplied value as you see fit. In this example, you can display the value of the argument as follows:

using System;

public class NewProject
{
	void DisplaySide(double Length)
	{
		Console.Write("Length: ");
		Console.WriteLine(Length);
	}
	static void Main()
	{
	}
}

In this case, remember to define the method as static if you plan to access it from Main(). In order to call a method that takes an argument, you must supply a value for the argument when calling the method; otherwise you would receive an error. Also, you should/must supply the right value; otherwise, the method may not work as expected and produce an unreliable result. Here is an example:

using System;

public class NewProject
{
	static void DisplaySide(double Length)
	{
		Console.Write("Length: ");
		Console.WriteLine(Length);
	}
	static void Main()
	{
		DisplaySide(35.55);
		
		Console.WriteLine();
	}
}

As mentioned already, a method that takes an argument can also declared its own variable. Such variables are referred to as local.

A method can take more than one argument. When defining such a method, provide each argument with its data type and a name. The arguments are separated by a comma.

 

Practical Learning Practical Learning: Passing Arguments

  1. To pass arguments to a method, change the file as follows:
     
    package Cylinder2;
    import System.*;
    
    public class Exercise
    {
    	static double GetTheRadius()
    	{
    		double rad;
    
    		do 
    		{
    			Console.Write("Radius: ");
    			rad = Double.parseDouble(Console.ReadLine());
    			if( rad < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( rad < 0 );
    		return rad;
    	}
    
    	static double GetTheHeight()
    	{
    		double h;
    
    		do 
    		{
    			Console.Write("Height: ");
    			h = Double.parseDouble(Console.ReadLine());
    			if( h < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( h < 0 );
    
    		return h;
    	}
    
    	static double CalculateBaseArea(double rad)
    	{
    		return rad * rad * Math.PI;
    	}
    
    	static double CalculateLateralArea(double rad, double hgt)
    	{
    		return 2 * Math.PI * rad * hgt;
    	}
    
    	static double CalculateTotalArea(double rad, double hgt)
    	{
    		return 2 * Math.PI * rad * (hgt + rad);
    	}
    
    	static double CalculateVolume(double rad, double hgt)
    	{
    		return Math.PI * rad * rad * hgt;
    	}
    
    	static void ProcessCylinder()
    	{
    		double radius;
    		double height;
    		double baseArea;
    		double lateralArea;
    		double totalArea;
    		double volume;
    
    		Console.WriteLine("Enter the dimensions of the cylinder");
    		radius = GetTheRadius();
    		height = GetTheHeight();
    	
    		baseArea    = CalculateBaseArea(radius);
    		lateralArea = CalculateLateralArea(radius, height);
    		totalArea   = CalculateTotalArea(radius, height);
    		volume      = CalculateVolume(radius, height);
    
    		Console.WriteLine("\nCylinder Characteristics");
    		Console.WriteLine("Radius:  {0}", (System.Double)radius);
    		Console.WriteLine("Height:  {0}", (System.Double)height);
    		Console.WriteLine("Base:    {0:F}", (System.Double)baseArea);
    		Console.WriteLine("Lateral: {0:F}", (System.Double)lateralArea);
    		Console.WriteLine("Total:   {0:F}", (System.Double)totalArea);
    		Console.WriteLine("Volume:  {0:F}", (System.Double)volume);
    	}
    	
    	public static void main(String[] args)
    	{
    		ProcessCylinder();
    	}
    }
  2. Save the file and switch to the Command Prompt
  3. Compile and execute the application. Here is an example:
     
    Enter the dimensions of the cylinder
    Radius: 35.96
    Height: 30.28
    
    Cylinder Characteristics
    Radius:  35.96
    Height:  30.28
    Base:    4062.46
    Lateral: 6841.56
    Total:   14966.49
    Volume:  123011.33
  4. Return to Notepad
 

Techniques of Passing Arguments

 

Passing Arguments by Value

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

 

Practical Learning Practical Learning: Passing Arguments By Value

  1. All the arguments we have used so far were passed by value. For one more example, change the program as follows:
     
    package Cylinder2;
    import System.*;
    import System.Math.*;
    
    public class Exercise
    {
    	static double GetTheRadius()
    	{
    		double rad;
    
    		do 
    		{
    			Console.Write("Radius: ");
    			rad = Double.parseDouble(Console.ReadLine());
    			if( rad < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( rad < 0 );
    		return rad;
    	}
    
    	static double GetTheHeight()
    	{
    		double h;
    
    		do {
    			Console.Write("Height: ");
    			h = Double.parseDouble(Console.ReadLine());
    			if( h < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( h < 0 );
    
    		return h;
    	}
    
    	static double CalculateBaseArea(double rad)
    	{
    		return rad * rad * Math.PI;
    	}
    
    	static double CalculateLateralArea(double rad, double hgt)
    	{
    		return 2 * Math.PI * rad * hgt;
    	}
    
    	static double CalculateTotalArea(double rad, double hgt)
    	{
    		return 2 * Math.PI * rad * (hgt + rad);
    	}
    
    	static double CalculateVolume(double rad, double hgt)
    	{
    		return Math.PI * rad * rad * hgt;
    	}
    
    	static void ProcessCylinder()
    	{
    		double radius;
    		double height;
    		double baseArea;
    		double lateralArea;
    		double totalArea;
    		double volume;
    
    		Console.WriteLine("Enter the dimensions of the cylinder");
    		radius = GetTheRadius();
    		height = GetTheHeight();
    	
    		baseArea    = CalculateBaseArea(radius);
    		lateralArea = CalculateLateralArea(radius, height);
    		totalArea   = CalculateTotalArea(radius, height);
    		volume      = CalculateVolume(radius, height);
    
    		ShowCylinder(radius, height, baseArea, lateralArea, totalArea, volume);
    	}
    
    	static void ShowCylinder(double rad, double hgt, double bArea,
    		double lateral, double total, double vol)
    	{
    		Console.WriteLine("\nCylinder Characteristics");
    		Console.WriteLine("Radius:  {0}", (System.Double)rad);
    		Console.WriteLine("Height:  {0}", (System.Double)hgt);
    		Console.WriteLine("Base:    {0:F}", (System.Double)bArea);
    		Console.WriteLine("Lateral: {0:F}", (System.Double)lateral);
    		Console.WriteLine("Total:   {0:F}", (System.Double)total);
    		Console.WriteLine("Volume:  {0:F}", (System.Double)vol);
    	}
    	
    	public static void main(String[] args)
    	{
    		ProcessCylinder();
    	}
    }
  2. Save the file, compile, and test it. Here is an example:
     
    Enter the dimensions of the cylinder
    Radius: 38.26
    Height: 28.48
    
    Cylinder Characteristics
    Radius:  38.26
    Height:  28.48
    Base:    4598.75
    Lateral: 6846.44
    Total:   16043.94
    Volume:  130972.40
  3. Return to Notepad

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 void 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");
	}
}

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 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.

Here are examples of passing some arguments by reference:

void Area(ref double Side); // The argument is passed by reference
bool Decision(ref char Answer, int Age); // One argument is passed by reference
// All arguments are passed by reference
float Purchase(ref float DiscountPrice, ref float NewDiscount, ref char Commission);

You add the ampersand when defining when calling the method. The above would be called with:

Area(ref Side);
Decision(ref Answer, Age);
Purchase(ref DiscountPrice, ref NewDiscount, ref Commission);

If you want a calling function to modify the value of an argument, you should supply its reference and not its value, using the ref keyword.

 

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 void Main()
	{
		double Number = 15.25;

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

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 void Main()
	{
		double Number = 15.25;

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

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 file as follows:
     
    using System;
    
    class Cylinder
    {
    	static void GetTheRadius(ref double rad)
    	{
    		do 
    		{
    			Console.Write("Radius: ");
    			rad = double.Parse(Console.ReadLine());
    			if( rad < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( rad < 0 );
    	}
    
    	static void GetTheHeight(out double h)
    	{
    		do 
    		{
    			Console.Write("Height: ");
    			h = double.Parse(Console.ReadLine());
    			if( h < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( h < 0 );
    	}
    
    	static double CalculateBaseArea(double rad)
    	{
    		return rad * rad * Math.PI;
    	}
    
    	static double CalculateLateralArea(double rad, double hgt)
    	{
    		return 2 * Math.PI * rad * hgt;
    	}
    
    	static double CalculateTotalArea(double rad, double hgt)
    	{
    		return 2 * Math.PI * rad * (hgt + rad);
    	}
    
    	static double CalculateVolume(double rad, double hgt)
    	{
    		return Math.PI * rad * rad * hgt;
    	}
    
    	static void ProcessCylinder()
    	{
    		double Radius = 0.00;
    		double Height = 0.00;
    		double BaseArea;
    		double LateralArea;
    		double TotalArea;
    		double Volume;
    
    		Console.WriteLine("Enter the dimensions of the cylinder");
    		GetTheRadius(ref Radius);
    		GetTheHeight(out Height);
    	
    		BaseArea    = CalculateBaseArea(Radius);
    		LateralArea = CalculateLateralArea(Radius, Height);
    		TotalArea   = CalculateTotalArea(Radius, Height);
    		Volume      = CalculateVolume(Radius, Height);
    
    		ShowCylinder(Radius, Height, BaseArea, LateralArea, TotalArea, Volume);
    	}
    
    	static void ShowCylinder(double rad, double hgt, double BArea,
    		                     double Lateral, double Total, double vol)
    	{
    		Console.WriteLine("\nCylinder Characteristics");
    		Console.WriteLine("Radius:  {0}", rad);
    		Console.WriteLine("Height:  {0}", hgt);
    		Console.WriteLine("Base:    {0:F}", BArea);
    		Console.WriteLine("Lateral: {0:F}", Lateral);
    		Console.WriteLine("Total:   {0:F}", Total);
    		Console.WriteLine("Volume:  {0:F}", vol);
    	}
    
    	static void Main()
    	{
    		ProcessCylinder();
    		
    		Console.WriteLine();
    	}
    }
  2. Compile and execute it. This would produce:
     
    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. Return to Notepad
 

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 function. Although two methods should have unique names in the same program, C# allows you to use the same name for different functions of the same program following certain rules. The ability to have various methods with the same name in the same program is referred to as overloading. The most important rule about function overloading is to make sure that each one of these methods has a different number or different type(s) of arguments.

The moment of inertia is the ability of 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.

We will illustrate method overloading through an exercise.

 

Practical Learning Practical Learning: Overloading a Method

  1. Start a new file in Notepad and type the following in it
     
    The Moment Of Inertia
    using System;
    
    public class NewProject
    {
    	// Rectangle
    	static double MomentOfInertia(double b, double h)
    	{
    		return b * h * h * h / 3;
    	}
    
    	static void 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();
    	}
    }
  2. Save it in a new folder named MOI1 inside your CSharp Lessons folder
  3. Save the file as Exercise.cs
  4. Switch to the Command Prompt and switch to the MOI1 folder that contains the above Exercise.cs file
  5. Compile and execute it. 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
  6. Return to Notepad
  7. 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 void 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();
    	}
    }
  8. Save the file. Then compile it and 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
  9. Return to Notepad
  10. 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 void 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();
    	}
    }

  11. Save the file. Then compile it and 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
  12. Return to Notepad
 

Previous Copyright © 2005-2016, FunctionX Next