Methods Fundamentals
|
Introduction
|
When you create a class, the fields are meant to
describe it. For a class named House, such aspects as the number of
bedrooms, the property type, or its value, are used to describe it:
|
public class House { public char propertyType; public uint 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. A method is simply a section of code
that takes care of a particular detail for the functionality of the class.
|
|
- Start Microsoft Visual Studio
- To create a new application, on the main menu, click File -> New Project
- In the middle list, click Empty Project
- Change the Name to DepartmentStore2 and click OK
- On the main menu, click Project -> Add New Item...
- In the middle list of the Add New Item dialog box, click Code File
- Change the name to StoreItem and click Add
- In the file, type the following:
public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; }
- To create a code file, in the Solution Explorer, right-click DepartmentStore2 -> Add -> New Item...
- In the middle list of the Add New Item dialog box, click Code File
- Change the name to DepartmentStore and click Add
- In the empty document, type the following:
public class DepartmentStore { static void Main() { StoreItem si = new StoreItem(); si.itemNumber = 720823; si.itemName = "Cotton Seam Sheath Dress"; si.size = "6"; si.unitPrice = 158M; 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(); } }
- Execute the application to see the result
- Close the DOS window and return to your programming environment
Creating 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:
-
If the name of a method is in one word, the first letter will be in uppercase
-
If the name of a method is a combination of words, the first letter of each word will be in uppercase
-
Because a method is an action, you should name it as a verb
The name of a method is followed by parentheses.
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. The type of value that a method can provide
(or return) is written on the left side of the method name. If the method
doesn't produce a result, type void to its left. The assignment that
a method carries is included between an opening curly bracket "{" and a
closing curly bracket "}". Here is an example:
public class House
{
public char propertyType;
public uint bedrooms;
void Display()
{
}
}
The most regularly used method of a C# program is called
Main.
|
New Convention:From now on, in our lessons, to refer to a method that belongs to a class, we may use the conventionClassName.MethodNameThis means that we are referring to the method MethodName that is a member of the class ClassName. |
The Access Modifier of a Method
|
Like a member variable:
- If the method will be accessed only by members of the same class, you can mark it as private or not mark it with an access modifier
- If the method will be accessed by members of the class and other parts of the same program but not outside of the program, mark it with the internal keyword
- In the method can be accessed by the members of the same class, other parts of the same program, and other parts of other programs, mark it as public
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 char propertyType; public uint 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 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 char propertyType;
public uint 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 . . .
- On the main menu, click Window -> StoreItem.cs to open that file
- To add some methods to the class, change the document as follows:
public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; public void CreateItem() { itemNumber = 792475; itemName = "Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray"; size = "3.4oz"; unitPrice = 48.00m; } 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); } }
- On the main menu, click Window -> DepartmentStore.cs
- Change the document as follows:
public class DepartmentStore { static void Main() { StoreItem si = new StoreItem(); si.CreateItem(); si.Describe(); System.Console.ReadKey(); } }
- Execute the application. This would produce:
Department Store Item #: 792475 Item Name: Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray Item Size: 3.4oz Unit Price: 48.00
- Close the DOS window and return to your programming environment
If a method has carried an assignment and must make its
result available to other methods or other classes, the method must return a
value and cannot be void. To declare a method that returns a value,
provide its return type to the left of its name. Here is an example:
class Exercise
{
double Operate()
{
}
}
You can also add a question mark to the data type. Here
is an example:
class Exercise
{
double? Operate()
{
}
}
In the body of a method, you can declare one or more
variables that would be used only by the method. A variable declared in the
body of a method is referred to as a local variable. The variable cannot be
accessed outside of the method it belongs to. After declaring a local
variable, it is made available to the method and you can use it as you see
fit, for example, you can assign it a value prior to using it.
After a method has performed its assignment, it must
clearly demonstrate that it is returning a value. To do this, you use the
return keyword followed by the value that the method is returning. The
value returned must be of the same type specified as the return type of the
method. Here is an example:
class Exercise
{
double Operate()
{
return 24.55;
}
}
This is also valid:
class Exercise
{
double? Operate()
{
return 24.55;
}
}
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;
}
}
|
- On the main menu, click Window -> StoreItem.cs
- Change the file as follows:
public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; public void CreateItem() { itemNumber = 792475; itemName = "Aramis Gentlemen Collection 3.4oz JHL Custom Blended Cologne Spray"; size = "3.4oz"; unitPrice = 48.00m; } public decimal 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()); } }
- Execute the application to see the result
- Close the DOS window and return to your programming environment
So far, we have used the Main() function as it is
defined by default when you create an application using the New Project
dialog box. This default implementation of the Main() function is of
type void. Another way to implement the Main() function is to
make it return an integer. The rule is the same as for any method of type
int. The Main() function can return any type of integer as long
as it is a valid integer. Here is an example:
class Exercise { char? HaveCharacter() { return 'G'; } static int Main() { Exercise exo = new Exercise(); System.Console.Write("Character: "); System.Console.WriteLine(exo.HaveCharacter()); return 244006; } }
This would produce:
Character: G Press any key to continue . . .
To create a Main function using skeleton code,
right-click the section where you want to add it and click Insert Snippet...
Double-click Visual C#:
- If you want to create a Main function that doesn't return a value,
double-click svm (stands for "static void Main")
- If you want to create a Main function that returns an integer, double-click sim (stands for "static int Main")
|
- Click the DepartmentStore.cs button to access it and change it as
follows:
public class DepartmentStore { static int Main() { StoreItem si = new StoreItem(); si.CreateItem(); si.Describe(); System.Console.ReadKey(); return 0; } }
- Execute the application to see the result
- Close the DOS window and return to your programming environment
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(char 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(char? 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(char c) { System.Console.WriteLine(c); } }
The following is also valid:
class Exercise
{
void ShowCharacter(char? c)
{
System.Console.WriteLine(c);
}
}
In the same way, you can manipulate the supplied value
as you see fit.
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(char c)
{
System.Console.WriteLine(c);
}
static int 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).
|
- Click the StoreItem.cs button to open its file and change it
as follows:
public class StoreItem { public long itemNumber; public string itemName; public string size; public decimal unitPrice; public void CreateItem() { itemNumber = 911792; itemName = "Girls Tillie Poplin Dress"; size = "12"; unitPrice = 110.00m; } public decimal CalculateTotalValue(int qty) { return unitPrice * qty; } public void Describe() { int quantity = 6; 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("Quantity: "); System.Console.WriteLine(quantity); System.Console.Write("Total Value: "); System.Console.WriteLine(CalculateTotalValue(quantity)); } }
- Execute the application to see the result:
Department Store Item #: 911792 Item Name: Petite Tropical Wool Pencil Skirt Item Size: 12 Unit Price: 110.00 Quantity: 6 Total Value: 660.00
- Close the DOS window and return to your programming environment
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(long employeeNumber, string fullName,
char 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 conventionClassName.MethodName(Arguments)This means that we are referring to the method MethodName that is a member of the class ClassName. 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 ClassName.MethodName(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. In reality, unlike C, C++, Object Pascal, Visual Basic, and some other languages, C# (and Java) doesn't allow forward definition. That is, you cannot first declare a function, then implement it in another section of the file or in another file (C# supports partial methods but that's not real forward definition, not in the sense of C, Pascal, and Visual Basic). We will use the semi-colon (or the only reason we will use the semi-colon) is to indicate the structure or skeleton of the method, not its actual definition. |
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(long employeeNumber, string fullName, char 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(long employeeNumber, string fullName,
char 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(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(long employeeNumber, string fullName,
char 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 . . .
|
- Close your programming environment
- When asked whether you want to save, click No
No comments:
Post a Comment