Introduction to the Methods of a Class
Introduction to the Methods of a Class
Methods Fundamentals
Introduction
When you create a class, the fields are meant to describe the objects created from that class. For a class named House, such aspects as the number of bedrooms, the property type, or its value, are used to describe it. Consider this class:
public class House { public string propertyType; public int bedrooms; }
Besides the characteristics used to describe it, an object can also perform actions or assignments. An action performed by a class is called a function or a method.
Practical Learning: Introducing Methods
public class StoreItem { public int itemNumber; public string itemName; public string size; public double unitPrice; }
public class DepartmentStore { static void Main() { StoreItem si = new StoreItem(); si.itemNumber = 720823; si.itemName = "Cotton Seam Sheath Dress"; si.size = "6"; si.unitPrice = 158; System.Console.WriteLine("Department Store"); System.Console.Write("Item #: "); System.Console.WriteLine(si.itemNumber); System.Console.Write("Item Name: "); System.Console.WriteLine(si.itemName); System.Console.Write("Item Size: "); System.Console.WriteLine(si.size); System.Console.Write("Unit Price: "); System.Console.WriteLine(si.unitPrice); System.Console.ReadKey(); } }
Introduction to Creating a Method
As seen for variables, the first piece of information you must provide about a method is a data type.
A Void Method
A method's job is to carry a specific assignment within a program. As such, it could provide a value once the assignment has been carried. In some cases, a method must produce a result. If it doesn't, then it is considered void. To create such a method, start with the void keyword.
A Name for a Method
To create a method, specify its name. The name of a method primarily follows the rules we defined for names of variables. Besides those rules, you can add yours. In our lessons, we will follow the same suggestions we reviewed for names of classes:
The name of a method is followed by parentheses.
The Body of a Method
The assignment that a method carries is included between an opening curly bracket "{" and a closing curly bracket "}". The section is referred to as the body of the method. Here is an example:
public class House
{
public string propertyType;
public int bedrooms;
void Display()
{
}
}
New Convention:From now on, in our lessons, to refer to a method that belongs to a class, we may use the convention class-name.method-name This means that we are referring to the method method-name that is a member of the class class-name. |
The Access Modifier of a Method
Like a member variable:
class Ceremony
{
string SpecifyType()
{
}
private string ObserveEtiquette()
{
}
}
After creating a method, in its body delimited by its curly brackets, you can define the desired behavior. For example, you can write the member variables in the parentheses of System.Console.Write() or System.Console.WriteLine(). Here are examples:
public class House { public string propertyType; public int bedrooms; internal void Display() { System.Console.WriteLine("=//= Altair Realtors =//="); System.Console.WriteLine("Properties Inventory"); ; System.Console.Write("Property Type: "); System.Console.WriteLine(PropertyType); System.Console.Write("Bedrooms: "); System.Console.WriteLine(Bedrooms); } }
In the same way, you can create as many methods as you want in a class.
After creating a method, you can access it, either inside or outside of its class. Accessing a method is referred to as calling it. You do this by following the same rules used to access a field, using the period operator. Unlike a field, the name of a class must be followed by parentheses. Here is an example:
public class House
{
public string propertyType;
public int bedrooms;
internal void Display()
{
System.Console.WriteLine("=//= Altair Realtors =//=");
System.Console.WriteLine("Properties Inventory"); ;
System.Console.Write("Property Type: ");
System.Console.WriteLine(propertyType);
System.Console.Write("Bedrooms: ");
System.Console.WriteLine(bedrooms);
}
}
public class Program
{
static void Main()
{
var property = new House();
property.propertyType = 'S';
property.bedrooms = 4;
property.Display();
}
}
This would produce:
=//= Altair Realtors =//= Properties Inventory Property Type: S Bedrooms: 4 Press any key to continue . . .
Practical Learning: Creating the Methods of a Class
public class StoreItem
{
public int itemNumber;
public string itemName;
public string size;
public double unitPrice;
public void CreateItem()
{
itemNumber = 792475;
itemName = "Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray";
size = "3.4oz";
unitPrice = 48.00;
}
public void Describe()
{
System.Console.WriteLine("Department Store");
System.Console.Write("Item #: ");
System.Console.WriteLine(itemNumber);
System.Console.Write("Item Name: ");
System.Console.WriteLine(itemName);
System.Console.Write("Item Size: ");
System.Console.WriteLine(size);
System.Console.Write("Unit Price: ");
System.Console.WriteLine(unitPrice);
}
}
public class DepartmentStore
{
static void Main()
{
StoreItem si = new StoreItem();
si.CreateItem();
si.Describe();
System.Console.ReadKey();
}
}
Department Store Item #: 792475 Item Name: Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray Item Size: 3.4oz Unit Price: 48.00
Introduction to Methods' Arguments
Overview
A method performs an assignment that completes the operations of a class. The methods we used in the previous sections relied on local 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 value(s). When a method needs a value to complete its assignment, such a value is called an argument.
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. Because a method must specify the type of value it would need, the argument is represented by its data type and a name.
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:
class Exercise
{
void ShowCharacter(string c)
{
}
}
If the data type of an argument is a primitive type, to indicate that it can hold a null value, add a question mark to it. Here is an example:
class Exercise
{
void ShowCharacter(string? c)
{
}
}
In the body of the method, you may or may not use the value of the argument. Here is an example that displays the value of the argument:
class Exercise { void ShowCharacter(string c) { System.Console.WriteLine(c); } }
The following is also valid:
class Exercise
{
void ShowCharacter(string? c)
{
System.Console.WriteLine(c);
}
}
In the same way, you can manipulate the supplied value as you see fit.
Calling a Method That Takes an Argument
As done for methods that don't take arguments, to use a method, you must call it. When calling a method that takes an argument, you must supply a value for the argument; otherwise you would receive an error. Also, you should/must supply the right value; otherwise, the method may not work as expected and it may produce an unreliable result.
If the method is taking an argument, when calling it, you can type a value in its parentheses. Here is an example:
class Exercise
{
void ShowCharacter(string c)
{
System.Console.WriteLine(c);
}
static void Main()
{
Exercise exo = new Exercise();
System.Console.Write("Character: ");
exo.ShowCharacter('W');
return 0;
}
}
A method that takes an argument can also declare its own local variable(s).
Practical Learning: Passing Arguments
|
Passing Many Arguments to a Method
A method can take more than one argument, provide each argument with its data type and a name. The arguments are separated by a comma. In the parentheses Here is an example:
class Exercise
{
void ShowEmployee(int employeeNumber, string fullName, string gender, double hourlySalary)
{
}
}
If necessary, you apply the question mark to one, some, or all arguments that are (is) of primitive type(s).
New Convention:From now on, in our lessons, to refer to a method that belongs to a class, we may use the convention class-name.method-name(Arguments) This means that we are referring to the method method-name that is a member of the class class-name. The item in the parentheses will refer to the argument(s) that the method takes. |
New Convention:From now on, in our lessons, we may write "The syntax of this method is" (or something to that effect): ReturnValue class-name.method-name(Arguments); This means that we are providing (reviewing) the return type, the name, and the number of arguments (if any) of a method. In our new convention, we terminate the syntax with a semi-colon. |
When defining the method, you can use 0, 1, or all arguments any way you like. For example, you can display their values using to the console. Here are examples:
class Exercise { void ShowEmployee(int employeeNumber, string fullName, string gender, double hourlySalary) { System.Console.Write("Employee #: "); System.Console.WriteLine(employeeNumber); System.Console.Write("Full Name: "); System.Console.WriteLine(fullName); System.Console.Write("Gender: "); System.Console.WriteLine(gender); System.Console.Write("Hourly Salary: "); System.Console.WriteLine(hourlySalary); } }
Although we saw already how to call a method that takes an argument, there are actually various ways this can be done. We saw that, when calling a method that takes an argument, you can type a value in the parentheses of the method. In the same way, when calling a method that takes more than one argument, type the appropriate value in the placeholder of each argument. Here are examples:
class Exercise
{
void ShowEmployee(int employeeNumber, string fullName, string gender, double hourlySalary)
{
System.Console.WriteLine("Employee Record");
System.Console.WriteLine("-----------------------------");
System.Console.Write("Employee #: ");
System.Console.WriteLine(employeeNumber);
System.Console.Write("Full Name: ");
System.Console.WriteLine(fullName);
System.Console.Write("Gender: ");
System.Console.WriteLine(gender);
System.Console.Write("Hourly Salary: ");
System.Console.WriteLine(hourlySalary);
}
static void Main()
{
Exercise exo = new Exercise();
exo.ShowEmployee(572948, "Andrew Bridges", 'M', 22.85D);
return 0;
}
}
This would produce:
Employee Record ----------------------------- Employee #: 572948 Full Name: Andrew Bridges Gender: M Hourly Salary: 22.85 Press any key to continue . . .
Calling an Argument by Name
lf you call a method that takes many arguments, you don't have to use the exact placeholder of each argument. Instead, you can refer to each argument by its name. To do this, in the parentheses of the method, type the name of an argument, followed by a colon, and followed by the appropriate value.
If you are using Microsoft Visual Studio, after typing the name of the method and the opening parentheses, you should see the list of names of the arguments:
You can then type the name of the argument. If you don't want to type, press Ctrl + Space. A menu would come. In its list would be the names of arguments:
You can either start typing until the name of an argument is selected or you can double-click from the list. As mentioned already, after the name of the argument, add a colon and a value for the argument. In the same way, you can access any argument by its name and give it a value, separate them with commas. Here is an example:
class Exercise
{
void ShowEmployee(int employeeNumber, string fullName, string gender, double hourlySalary)
{
System.Console.WriteLine("Employee Record");
System.Console.WriteLine("-----------------------------");
System.Console.Write("Employee #: ");
System.Console.WriteLine(employeeNumber);
System.Console.Write("Full Name: ");
System.Console.WriteLine(fullName);
System.Console.Write("Gender: ");
System.Console.WriteLine(gender);
System.Console.Write("Hourly Salary: ");
System.Console.WriteLine(hourlySalary);
}
static int Main()
{
Exercise exo = new Exercise();
exo.ShowEmployee(fullName: "Annette Greens", hourlySalary: 16.85, employeeNumber: 519427, gender: 'F');
return 0;
}
}
This would produce:
Employee Record ----------------------------- Employee #: 519427 Full Name: Annette Greens Gender: F Hourly Salary: 16.85 Press any key to continue . . .
The Scope and Lifetime of a Variable
Introduction
The scope of a variable is the extent to which it is available to other members of a class. To manage this, a variable is said to have local or global scope.
Local Variables
A variable is said to be local if it is declared in the body of a method. Here is an example:
class MemberRegistration
{
private void Create()
{
string middleName;
}
}
When a variable is declared as local, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error.
A Global Variable
A variable is said to be global if it is declared inside in the body of a class and outside the curly brackets of any method. Here is an example:
class MemberRegistration
{
string strDateOfBirth;
private void Initialize()
{
}
private void Present()
{
}
}
A variable that has been declared globally can be accessed by any code of the same class.
The Scope and Lifetime of an Object
You can declare a variable of a class in the body of a class and initialize it there. Here is an example:
class Student
{
}
class StudentRegistration
{
Student pupil = new Student();
private void Show()
{
}
}
Once this has been done, the object is ready to be used by any method of the same class. As an alternative, you can declare the variable in the body of the class but initialize it in a method of the class. Here is an example:
class Student { } class StudentRegistration { Student pupil; private void Create() { pupil = new Student(); } private void Show() { } }
If you decide to use this technique, before the object can be actually used, you must call the method that initializes the variable, otherwize you may receive an error.
Introduction
A method can be made to return a value. In fact, a method can also be made to return an object. To indicate that a method is returning a value, when creating that method, the first requirement is that, on the left side of its name, instead of the void keyword, specify a data type. Here is an example:
class Rectangle { public double Width; public double Height; public double Area() { } }
The second requirement is that, in the body of the function or a method, you must indicate the value it returns. There are many ways you can do this but the primary technique is that, before the closing curly bracket, type the return keyword followed by the value and a semicolon. Here is an example:
class Rectangle
{
public double Width;
public double Height;
public double Area()
{
double result = 0.00;
return result;
}
}
Otherwise, you can perform any operation in the body of the method and return the desired value. Here is an example:
class Rectangle
{
public double Width;
public double Height;
public double Area()
{
double result = 0.00;
result = Width * Height;
return result;
}
}
Practical Learning: Creating a Method that Returns a Value
public class TimeSheet { public double Week1TimeWorked; public double Week2TimeWorked; public double HourlySalary; public void Initialize(double hSalary, double week1, double week2) { Week1TimeWorked = week1; Week2TimeWorked = week2; HourlySalary = hSalary; } public double CalculateBiweeklySalary() { double result = 0; double totalTimeWorked = Week1TimeWorked + Week2TimeWorked; result = HourlySalary * totalTimeWorked; return result; } }
Introduction to Calling a Method that Returns a Value
To use the value that a method returns, you must call that method. If you want, you can assign its value to a local variable.
Practical Learning: Calling a Method that Returns a Value
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="~/Content/Site.css" /> <title>Fun Department Store - Payroll Preparation</title> </head> <body> @{ double netPay = 0; double hourlySalary = 0; TimeSheet ts = new TimeSheet(); if (IsPost) { hourlySalary = Request["txtHourlySalary"].Asdouble(); double week1TimeWorked = Request["txtWeek1TimeWorked"].AsDecimal(); double week2TimeWorked = Request["txtWeek2TimeWorked"].AsDecimal(); ts.Initialize(hourlySalary, week1TimeWorked, week2TimeWorked); netPay = ts.CalculateBiweeklySalary(); } } <div class="container"> <h1>Fun Department Store</h1> <h2>Payroll Preparation</h2> <form name="frmPayrollPreparation" method="post"> <table> <tr> <td class="left-col emphasize">Hourly Salary:</td> <td><input type="text" name="txtHourlySalary" value="@hourlySalary" /></td> </tr> <tr> <td colspan="2" class="emphasize">Time Worked</td> </tr> <tr> <td class="left-col emphasize">Week 1:</td> <td><input type="text" name="txtWeek1TimeWorked" value="@ts.Week1TimeWorked" /></td> </tr> <tr> <td class="emphasize">Week 2:</td> <td><input type="text" name="txtWeek2TimeWorked" value="@ts.Week2TimeWorked" /></td> </tr> <tr> <td> </td> <td><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> <tr> <td class="emphasize">Biweekly Salary:</td> <td><input type="text" name="txtBiweeklySalary" value="@netPay.ToString("F")" /></td> </tr> </table> </form> </div> </body> </html>
public class TimeSheet { public double Week1TimeWorked; public double Week2TimeWorked; public double HourlySalary; public void Initialize(double hSalary, double week1, double week2) { Week1TimeWorked = week1; Week2TimeWorked = week2; HourlySalary = hSalary; } public double CalculateBiweeklySalary() { double result = 0; result = HourlySalary * (Week1TimeWorked + Week2TimeWorked); return result; } }
public class TimeSheet { public double Week1TimeWorked; public double Week2TimeWorked; public double HourlySalary; public void Initialize(double hSalary, double week1, double week2) { Week1TimeWorked = week1; Week2TimeWorked = week2; HourlySalary = hSalary; } public double CalculateBiweeklySalary() { double result = HourlySalary * (Week1TimeWorked + Week2TimeWorked); return result; } }
public class TimeSheet { public double Week1TimeWorked; public double Week2TimeWorked; public double HourlySalary; public void Initialize(double hSalary, double week1, double week2) { Week1TimeWorked = week1; Week2TimeWorked = week2; HourlySalary = hSalary; } public double CalculateBiweeklySalary() { return HourlySalary * (Week1TimeWorked + Week2TimeWorked); } }
A Method that Returns an Expression
A method can also return an expression, provided the expression produces a value that is conform to the return type. Here is an example:
class Exercise
{
double Operate()
{
return 24.55 * 4.16;
}
}
A Simple Returning Method with no Body
If you have a method that either contains only one expression or the contents of its body can be resumed to one line, such a method doesn't need a body. Instead, after the parentheses of the method, type => followed by the returning expression. Here is an example:
class Contractor
{
public int ContractorCode;
public string FirstName;
public string LastName;
public double HourlySalary;
public string ContractorName() => FirstName + " " + LastName;
}
Practical Learning: Using a Method without a Body
public class TimeSheet
{
public double Week1TimeWorked;
public double Week2TimeWorked;
public double HourlySalary;
public void Initialize(double hSalary, double week1, double week2)
{
Week1TimeWorked = week1;
Week2TimeWorked = week2;
HourlySalary = hSalary;
}
public double CalculateBiweeklySalary() => HourlySalary * (Week1TimeWorked + Week2TimeWorked);
}
Techniques of Calling a Method that Returns a Value
You can call a function or method that returns a value as you do for one that is void. If you want to get and use the value returned by the method, you can declare a variable of the return type and assign the call to that variable. The variable would then be carrying the return value of the method and you can use that value any way you want.
class Contractor
{
public string FirstName;
public string LastName;
public string ContractorName() => FirstName + " " + LastName;
}
class Employment
{
static void Main()
{
string fullName = "";
string fName = "Jennifer";
string lName = "Clarenden";
Contractor staff = new Contractor();
staff.FirstName = fName;
staff.LastName = lName;
fullName = staff.ContractorName();
System.Console.WriteLine("=//= Department Store =//=");
System.Console.WriteLine("============================");
System.Console.Write("Employee Name: ");
System.Console.WriteLine(fullName);
}
}
This would produce:
=//= Department Store =//= ============================ Employee Name: Jennifer Clarenden Press any key to continue . . .
In the above code, we first declared a variable in one line and called the method in another line. This is done in case the values of the variable may change. Otherwise, you can declare the variable on the same line where you are calling the method. Here is an example:
class Contractor
{
public string FirstName;
public string LastName;
public string ContractorName() => FirstName + " " + LastName;
}
class Employment
{
static void Main()
{
string fName = "Jennifer";
string lName = "Clarenden";
Contractor staff = new Contractor();
staff.FirstName = fName;
staff.LastName = lName;
string fullName = staff.ContractorName();
System.Console.WriteLine("=//= Department Store =//=");
System.Console.WriteLine("============================");
System.Console.Write("Employee Name: ");
System.Console.WriteLine(fullName);
}
}
In the previous two examples, we declared a variable to store the return value of the method. This is done if you plan to use the variable many times, or call the method many times, or if the value of the variable will change more than once. If you are planning to call the method once, of if you don't need to store its value in a variable, you can call the method directly where its value is needed. Here is an example:
class Contractor
{
public string FirstName;
public string LastName;
public string ContractorName() => FirstName + " " + LastName;
}
class Employment
{
static void Main()
{
string fName = "Jennifer";
string lName = "Clarenden";
Contractor staff = new Contractor();
staff.FirstName = fName;
staff.LastName = lName;
System.Console.WriteLine("=//= Department Store =//=");
System.Console.WriteLine("============================");
System.Console.Write("Employee Name: ");
System.Console.WriteLine(staff.ContractorName());
}
}
Practical Learning: Returning a Value From a Method
public class StoreItem { public int itemNumber; public string itemName; public string size; public double unitPrice; public void CreateItem() { itemNumber = 792475; itemName = "Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray"; size = "3.4oz"; unitPrice = 48.00; } public double CalculateTotalValue() { return unitPrice; } public void Describe() { System.Console.WriteLine("Department Store"); System.Console.Write("Item #: "); System.Console.WriteLine(itemNumber); System.Console.Write("Item Name: "); System.Console.WriteLine(itemName); System.Console.Write("Item Size: "); System.Console.WriteLine(size); System.Console.Write("Unit Price: "); System.Console.WriteLine(unitPrice); System.Console.Write("Total Value: "); System.Console.WriteLine(CalculateTotalValue()); } }
If you are creating a method that may or may not return a value, you can indicate that it may return null. To do this, add a question mark to the data type. Here is an example:
class Exercise
{
double? Operate()
{
}
}
In the body of a method, perform any necessary operation such as declaring one or more local variables. At the end of the method, use the return keyword to produce the desired value. Here is an example:
class Exercise
{
double? Operate()
{
return 24.55;
}
}
Having Many Methods that Return the Same Type of Value
Imagine you have a method that returns a value or an expression. Here is an example:
public class Operation
{
public double Number1;
public double Number2;
public string Operator;
public string Calculate()
{
return Number1.ToString() + Operator + Number2.ToString();
}
}
If you need another method that performs the same type of operation and/or returns the same type of value, you don't need to declare a variable to call the first method. Here is an example:
public class Operation
{
public double Number1;
public double Number2;
public string Operator;
public string Calculate()
{
return Number1.ToString() + Operator + Number2.ToString();
}
public string Add()
{
return Calculate();
}
}
In the same way, you can have other methods that call that method. Here are examples:
public class Operation { public double Number1; public double Number2; public string Operator; public string View() { return Number1.ToString() + Operator + Number2.ToString(); } public string Add() { return Calculate(); } public string Subtract() { return Calculate(); } public string Multiply() { return Calculate(); } }
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|