Introduction to the Methods of a Class
Introduction to the Methods of a Class
Methods Fundamentals
Introduction
A method is a function that is a member of a class. A method follows the exact same descriptions and rules we reviewed for functions. In our lessons, sometimes we may use the words "function" and "method" interchangeably; just keep in mind that a method is a function that is in a class. We also say that a method is a function that belongs to a class, or that a method belongs to a class.
Practical Learning: Introducing Classes
namespace PieceWork4.Pages { public class Driver { public string first_name; public string last_name; } }
namespace PieceWork4.Pages { /* Piecework is the type of work that is paid on the number * of items produced, the distance driven, etc. * In this exercise, a business uses trucks driven by some * employees or contractors to deliver some products. * The drivers are paid based on the distance they travel to * deliver one or many products. */ public class Truck { public string make; public string model; } }
@page
@model PieceWork2.Pages.PieceDeliveryModel
@{
int miles = 0;
double pieceworkRate = 0.00;
Truck trk = new Truck();
Driver drv = new Driver();
drv.first_name = "Jeannette";
drv.last_name = "Dumont";
trk.make = "Chevrolet";
trk.model = "LCF 4500 Regular Cab 4x2";
double pay = miles * pieceworkRate;
string strPay = $"{pay:F}";
}
<h3 style="text-align: center"> - Piece Work Delivery -</h3>
<hr />
<table width="350" align="center">
<tr>
<td width="125">Driver:</td>
<td>@drv.first_name @drv.last_name</td>
</tr>
<tr>
<td>Truck Details:</td>
<td>@trk.make @trk.model</td>
</tr>
</table>
<hr />
<table align="center" width="350">
<tr>
<td width="125">Miles Driven:</td>
<td>@miles</td>
</tr>
<tr>
<td>Piecework Rate:</td>
<td>@pieceworkRate</td>
</tr>
<tr>
<td>Gross Salary:</td>
<td>@strPay</td>
</tr>
</table>
- Piece Work Delivery - Driver: Jeannette Dumont Truck Details: Ford E-350 4x2 Rockport Cutaway Van Miles Driven: 0 Piecework Rate: 0 Gross Salary: 0.00
Creating a Method
As seen with functions, the primary formula to create a method is:
options return-type method-name(){}
The main difference between a function and a method is that a method must be created in the body of a class. Here is an example:
@{
class Vehicle
{
options CarryMe()
{
}
}
}
New Convention:From now on, in our lessons, to refer to a method of 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 function-member of the class class-name. |
Practical Learning: Creating Methods
@page @model PieceWork2.Pages.PieceDeliveryModel @{ int miles; double pieceworkRate; Truck trk = new Truck(); Driver drv = new Driver(); drv.first_name = "Jeannette"; drv.last_name = "Dumont"; trk.make = "Chevrolet"; trk.model = "LCF 4500 Regular Cab 4x2"; double pay = miles * pieceworkRate; string strPay = $"{pay:F}"; } @{ // A method that requests a value void GetMiles() { miles = 1417; } // A method that requests a value void GetWorkRate() { pieceworkRate = 0.47; } } . . .
Code Sections Delimiters
Microsoft Visual Studio provides various techniques to assist you with code writing and management. The characteristics include color-coded words, intuitive indentation, the IntelliSense, delimitation of sections of code, etc. Consider the following contents of the Code Editor based on what we have reviewed so far:
Notice that there are - buttons (dash buttons) on the left side of some lines of code. These allow you to collapse a section of code if you think you don't need to see it. To do this, you can click the - button (the dash button). If you click that - button, it changes into a + button (a plus button). Here is an example:
The + button allows you to expand a hidden code section. This behavior of creating + and - buttons is part of the Code Editor of Microsoft Visual Studio. To create these sections, the Code Editor follows some rules. For example, it looks for the start and end of such an item as a function.
Regions
Besides, or instead of, the sections of code created by the Code Editor, if you want, you can create your own sections. To create a section:
#region Whatever
and end it with
#endregion Whatever
When and where you start a region, the #region expression is required. On the right side of this expression, you can type anything you want on the line. To end the section, type #endregion, followed by anything you want. Consider the following example:
int someVariable; #region This section is reserved for quadrilateral shapes void ProcessRectangle() { } void ShowSquare() { } #endregion This is the end of the quadrilateral section string message;
You don't have to type anything on the right side of #endregion. After creating the region, the Code Editor would display a - button (dash) to the left side of #region with a line from there to the left of #endregion:
This then allows you to expand and collapse that section at will:
We mentioned that you didn't have to type anything on the right side of #endregion and you could leave it empty. In our example, notice that there is a rectangle with gray lines around the string that follows #region. This rectangle doesn't cover the string that follows #endregion. This means that if you don't type anything on the right side of #endregion, that section on the right side of the #region line would not show.
Calling a Method
If you create a method, other members, including methods, of the same class can access that method directly. In the previous lessons, we saw that, before accessing a member of a class, first create an object of that class. On that object, type a period and the desired member. This also applies to a method, except that a method must use parentheses. Accessing a method is also referred to as calling it.
Practical Learning: Calling Methods
@page @model PieceWork2.Pages.PieceDeliveryModel @{ int miles = 0; double pieceworkRate = 0.00; Truck trk = new Truck(); Driver drv = new Driver(); drv.first_name = "Jeannette"; drv.last_name = "Dumont"; trk.make = "Chevrolet"; trk.model = "LCF 4500 Regular Cab 4x2"; // Get the number of miles driven GetMiles(); // Get the pay rate GetWorkRate(); double pay = miles * pieceworkRate; string strPay = $"{pay:F}"; } @{ void GetMiles() { miles = 1417; } void GetWorkRate() { pieceworkRate = 0.47; } } <h3 style="text-align: center"> - Piece Work Delivery -</h3> <hr /> <table width="350" align="center"> <tr> <td width="125">Driver:</td> <td>@drv.first_name @drv.last_name</td> </tr> <tr> <td>Truck Details:</td> <td>@trk.make @trk.model</td> </tr> </table> <hr /> <table align="center" width="350"> <tr> <td width="125">Miles Driven:</td> <td>@miles</td> </tr> <tr> <td>Piecework Rate:</td> <td>@pieceworkRate</td> </tr> <tr> <td>Gross Salary:</td> <td>@strPay</td> </tr> </table>
- Piece Work Delivery - Driver: Jeannette Dumont Truck Details: Chevrolet LCF 4500 Regular Cab 4x2 Miles Driven: 1417 Piecework Rate: 0.47 Gross Salary: 665.99
The Access Modifier of a Method
As mentioned in previous lessons, if you want a member of a class, including a method, to be accessed outside that class, you must mark that member with an appropriate access level. As a result, when creating a method, the primary option you can provide is its access level. Like any member of a class:
Here is an example of a method marked with an access level and accessed outside the class:
@page @model Valuable.Pages.FoundationsModel @{ Vehicle transport = new Vehicle(); transport.CarryMe(); } @functions{ public class Vehicle { internal void CarryMe() { } } }
The Scope and Lifetime of an Object
In our introduction to functions, we saw that a variable can be declared in the body directly in the document of a Code Editor. Such a variable is said to be global. We also saw that a variable can be declared in the body of a function. Such a variable is said to be local.
You can declare a variable of a class in the body of a class and initialize it there. Here is an example:
@functions{
public class Student
{
}
public class StudentRegistration
{
Student pupil = new Student();
private void Show()
{
}
}
}
Once this has been done, the variable can be used in 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:
@functions{ public class Student { } public class StudentRegistration { Student pupil; void Create() { pupil = new Student(); } void Show() { } } }
If you decide to use this technique, before the variable can be used, you must call the method that initializes the variable, otherwise you may receive an error.
Introduction
Practically every function or method has a body, which is delimited by curly brackets. As seen with functions, to indicate the end of execution of a method, type the return keyword followed by a semicolon. Here are examples:
@functions{ class Exercise { void Communicate() { return; } void NeedToDiscuss() { return; } void Summarize() { return; } } }
Returning From a Method
Like a function, a method can return a value. If a method doesn't produce an explicit value, mark its return type as void. Otherwise, if a method produces a value, write the desired data type on the left side of the name of the method. Here is an example:
@functions{
class Rectangle
{
public double Width;
public double Height;
public double Area()
{
}
}
}
Before the closing curly bracket of the method, type the return keyword and what to return, followed by a semicolon.
Like a function, a method can return a constant value. Here is an example:
@functions{
public class Calculation
{
int GetTriple()
{
return 3000;
}
}
}
Otherwise, you can first declare a value and return it from the method. Here is an example:
@functions{
class Numerical
{
int GetTriple()
{
int result = Number * 3;
return result;
}
}
}
Like a function, a method can return an expression. Consider the above GetTriple method. As seen with functions, if the code of a method is short, you can remove the body of the method delimited by curly brackets. Then, after the parentheses of the method, type => followed by the returning expression and a semicolon. Here is an example:
@functions{
class Numerical
{
int GetTriple() => nbr * 3;
}
}
As seen with functions, if you have a method that produces a value that is used only once, you can assign the method to a variable and then use that variable as you see fit. Here are examples:
@functions{
int GetTriple()
{
return 3000;
}
}
@{
int value = 3250;
double total = GetTriple();
}
As seen with functions, if you are not planning to use the returned value of a method many times, you can call the method directly where its value is needed.
As mentioned with functions, instead of storing the returned value of a method in a variable, you can call the method directly on the return line. Here are examples:
@page @model Valuable.Pages.FoundationsModel @{ Exercise exo = new Exercise(); exo.nbr = 44; } @functions{ public class Exercise { public int nbr; int Time4() { return nbr * 4; } int Calculate() { int u = 38; int w = nbr * 3; return u + w; } public int GetNumber() { int x = 428; nbr = x; return Time4(); } public int Summarize() { int y = 3_258; nbr = y * 8; return Calculate(); } } } <pre>Number: @exo.GetNumber() Summary: @exo.Summarize()</pre>
This would produce:
Number: 1712 Summary: 78230
Calling a Method that Returns a Value
When you call a method that returns a value, you follow the exact same techniques and options we saw for functions. The only difference is that you must qualify the method by an object of its class
Nesting a Method
As mentioned in our introduction, a function or method is a section of code that solves a specific problem. Sometimes, you will find out that a method you had created is useful to only one other method. This means that, in this case, only a certain method calls a certain method and no other method calls that method B. If you have a section of code that only a certain method calls, you can create a function for that section in the body of the unique method that calls it.
A local function is a function that is created in the body of a method. A function created inside a method is also referred to as nested. The C# language provides various options to nest a function.
You primarily create a local function like any other, as long as you create it in the body of a method. After creating a nested function, call it by its name as we have done for the others.
Methods and Parameters
A Method with a Parameter
Like a function, a method of a class can use a parameter. When creating the method, make sure you provide the data type of the parameter and its name in the parentheses of the method. Here is an example:
@functions{
public class Attachment
{
void Prepare(int number)
{
}
}
}
New Convention:From now on, in our lessons, we may write "The syntax of this method is" (or something to that effect): return-type class-name.method-name(data-type parameter-name); This means that we are referring to the method method-name that is a member of the class class-name and that uses one parameter specified by the indicated data type. We may also mention (or review) the return type of the method. |
When calling the method from an object of the class, make sure you pass an appropriate value as argument.
A Methods with many Parameters
You can create a method that takes more than one parameter. To prepare the arguments, in the parentheses of the method, create each parameter with its data type and a name. The parameters are separated by comas. Here are examples:
@functions{ public class Attachment { void Prepare(int number) { } void Upload(string location) { } void Download(string location, int size) { } void Indicate(int id, string code, int age, double cost) { } } }
New Convention:From now on, in our lessons, we may write "The syntax of this method is" (or something to that effect): return-type class-name.method-name(parameter(s)); This means that we are referring to the method method-name that is a member of the class class-name and that uses the parameter(s) specified. We may also provide (or review) the return type of the method. |
In the body of a method, you don't have to use a parameter or all parameters. This means that you can completely ignore the parameter. Otherwise, in the body of the method, you can use the parameter in any appropriate way you want.
Method Overloading
Introduction
The signature of a function or method is a combination of its name and the type(s) of its parameter(s), if any. The return type and the symbols (such as the parentheses and the curly brackets) are not part of the signature of a function or method. Since some functions or methods don't take any parameter, the signature of such functions or methods is only the name of the function or method. Consider the following method:
@functions{ public class { void Consist() { } } }
The signature of that method is:
Consist
Consider the following method:
@functions{ public class { double Consist() { } } }
The signature of that method too is:
Consist
Notice that both methods use the same name. Also notice their return types, void and double. Regardless of the return types, since those methods use the same name and they don't use any parameter, they have the same signature. Consider a method as follows:
@functions{ public class { int Consist(string characters) { } } }
If a method uses one parameter, its signature consists of its name and the data type of the parameter, as in:
method-name#parameter-type
As a result, the signature of the above method is:
Count#string
If a method uses two parameters, its signature consists of its name and the data types of the parameters in the order they appear, as in:
method-name#parameter_1-type#parameter_2-type
If a method uses more parameters, its signature consists of its name and the data types of the parameters in the order they appear, as in:
method-name#parameter_1-type#parameter_2-type#parameter_n-type
Overloading a Method
Method overloading is the ability to have two or more methods with the same name in the same class. The primary rule (probably the only rule) is that the overloaded methods cannot have the same signature.
To perform method overloading, each version of the overloaded method must have a different signature. Consider the following class:
@functions{ public class Geometry { // Square double CalculateArea(double side) { return side * side; } // Circle double CalculateArea(double radius) { return radius * radius * 3.14159; } } }
That code will produce an error because both methods have the same signature. There are two main options you can use to solve method overloading issues. One of the solutions to perform method overloading is that the parameters of the methods use different data types. Here is an example:
@functions{ public class Payroll { double CalculateBiweeklySalary(double yearlySalary) { return yearlySalary / 24.00; } // A full-time employee with a fixed yearly salary double CalculateBiweeklySalary(string monthlySalary) { double salary = double.Parse(monthlySalary); return monthlySalary / 2.00; } } }
Another option is that each method can use a different number of parameters. Based on this, if you insist on having various methods that use the exact same signature, simply add an extra parameter to some of them and don't use that extra parameter in the method.
Practical Learning: Ending the Lethod
|
|||
Previous | Copyright © 2001-2023, C# Key | Tuesday 16 November 2021 | Next |
|