989 lines
40 KiB
Markdown
989 lines
40 KiB
Markdown
|
# Call methods from the .NET Class Library using C#
|
|||
|
|
|||
|
## Introduction
|
|||
|
|
|||
|
The C# programming language is supplemented by a large library of
|
|||
|
functionality that enables you to create applications, access data in files or
|
|||
|
on the Internet, perform advanced mathematical operations, and much more.
|
|||
|
Understanding how to navigate this library of functionality is a critical
|
|||
|
skill that will help you build feature-rich applications more quickly.
|
|||
|
|
|||
|
Suppose you need to generate a daily report that's based on thousands of data
|
|||
|
files. To save time, your code uses a random sample of the data files to
|
|||
|
calculate an approximate result without analyzing all the data files. How can
|
|||
|
you generate a random number? Is this supported by C#? If so, how can you
|
|||
|
write code to set the value range for a random number, and then generate and
|
|||
|
retrieve the result?
|
|||
|
|
|||
|
In this module, you learn about class libraries, and write code that calls
|
|||
|
methods in the .NET Class Library. You learn the characteristics of methods,
|
|||
|
and why methods of the .NET Class Library are designed and implemented
|
|||
|
differently across the .NET Class Library. Most importantly, you write code
|
|||
|
that uses the .NET Library methods to achieve a specific programming task.
|
|||
|
Finally, you'll use built-in tools and online documentation to help you gather
|
|||
|
information about the methods you want to work with.
|
|||
|
|
|||
|
By the end of this module, you'll know how to find classes and methods in the
|
|||
|
.NET Class Library, and how to use them to perform common programming tasks.
|
|||
|
|
|||
|
> Important
|
|||
|
> This module includes coding activities that require Visual Studio Code. You
|
|||
|
'll need access to a development environment that has Visual Studio Code
|
|||
|
installed and configured for C# application development.
|
|||
|
|
|||
|
#### Learning Objectives
|
|||
|
|
|||
|
In this module, you will:
|
|||
|
|
|||
|
- Write code that calls methods in the .NET Class Library.
|
|||
|
- Use an instance of .NET Class Library classes to call methods that maintain
|
|||
|
state.
|
|||
|
- Use Intellisense in Visual Studio Code to learn more about a method,
|
|||
|
including its overloaded versions, its return value type, and its input
|
|||
|
parameter data types.
|
|||
|
- Use learn.microsoft.com to research what a method does, its overloaded
|
|||
|
versions, its return value type, its input parameters and what each parameter
|
|||
|
represents, and more.
|
|||
|
|
|||
|
#### Prerequisites:
|
|||
|
|
|||
|
- Experience using Visual Studio Code to create and run C# console applications.
|
|||
|
- Experience using the basic C# data types including int and string.
|
|||
|
- Experience using the Console.WriteLine() method.
|
|||
|
|
|||
|
---
|
|||
|
|
|||
|
## Get started with .NET Libraries
|
|||
|
|
|||
|
There's more to building a C# application than stringing together lines of code.
|
|||
|
You'll need the .NET Runtime, which hosts and manages your code as it executes
|
|||
|
on the end user's computer. You'll also rely on the .NET Class Library, a
|
|||
|
prewritten collection of coding resources that you can use in your applications.
|
|||
|
This unit explains what the .NET Class Library is and how it complements the
|
|||
|
C# programming language.
|
|||
|
|
|||
|
### What is the .NET Class Library?
|
|||
|
|
|||
|
When you need to find a book, a public library is a good place to look. After
|
|||
|
all, libraries contain thousands and thousands of books, and they're organized
|
|||
|
into sections that help you to find what you're looking for. When you need to
|
|||
|
implement a programming task, the .NET Class Library is a good place to look,
|
|||
|
because it's an organized collection of programming resources.
|
|||
|
|
|||
|
The .NET Class Library is a collection of thousands of classes containing tens
|
|||
|
of thousands of methods. For example, the .NET Class Library includes the
|
|||
|
Console class for developers working on console applications. The Console
|
|||
|
class includes methods for input and output operations such as `Write()`,
|
|||
|
`WriteLine()`, `Read()`, `ReadLine()`, and many others. For example, you may
|
|||
|
already be familiar with the following code:
|
|||
|
|
|||
|
```cs
|
|||
|
Console.WriteLine("Hello, World!")
|
|||
|
```
|
|||
|
|
|||
|
You can think of a class as a container for methods, kind of like the sections
|
|||
|
of the public library. Developers typically keep related methods together in a
|
|||
|
single class. As you saw in the previous example, any methods that can send or
|
|||
|
receive information from a console window are collected into the `System.Console`
|
|||
|
class in the .NET Class Library.
|
|||
|
|
|||
|
In many cases, these classes and methods enable you to build a specific type
|
|||
|
of application. For example, one of the larger subsets of classes and methods
|
|||
|
enable you to create dynamic web applications. There's also several families
|
|||
|
of classes that enable you to build native desktop applications. Another
|
|||
|
subset of classes and methods enable you to access a database. There are lots
|
|||
|
of classes in the .NET Class Library that support specific types of applications.
|
|||
|
|
|||
|
There are other classes with methods that provide support in a more general way.
|
|||
|
In other words, their utility spans a wide range of device platforms,
|
|||
|
application frameworks, and technology areas. For example, if you want to read
|
|||
|
or write file information, or perform trigonometry or calculus operations,
|
|||
|
there are general purpose classes that you can use in your code. It doesn't
|
|||
|
matter whether you're building applications for the web, desktop, mobile device,
|
|||
|
or the cloud, general purpose classes and methods are there to help.
|
|||
|
|
|||
|
As you can imagine, having a massive library of functionality available to
|
|||
|
your applications is a huge time saver for you as a software developer. The
|
|||
|
classes and methods in the .NET Class Library are created by Microsoft and are
|
|||
|
available for use in your applications.
|
|||
|
|
|||
|
### Even data types are part of the .NET Class Library
|
|||
|
|
|||
|
C# data types (such as string and int) are actually made available through
|
|||
|
classes in the .NET Class Library. The C# language masks the connection
|
|||
|
between the data types and the .NET classes in order to simplify your work.
|
|||
|
However, behind the scenes, the data types are implemented just like every
|
|||
|
other class in the .NET Class Library. This connection provides your everyday
|
|||
|
variables with built-in methods that can be very helpful. The string class has
|
|||
|
lots of these helpful methods. For example, the string class has methods for
|
|||
|
converting text to uppercase and lowercase (ToUpper and ToLower).
|
|||
|
|
|||
|
#### How to find what you need in the .NET Class Library
|
|||
|
|
|||
|
With so many classes and methods, how can you find what you need for your
|
|||
|
application?
|
|||
|
|
|||
|
First of all, remember that finding every class and method in the .NET Class
|
|||
|
Library is like finding every book in a large public library. You don't need
|
|||
|
every book in the library, and you won't be using every class and method in
|
|||
|
the .NET Class Library. Depending on the types of projects that you work on,
|
|||
|
you'll become more familiar with some parts of the .NET Class Library and less
|
|||
|
familiar with others. Again, it's like spending time in a section of the
|
|||
|
public library, over time you become familiar with what's available. No one
|
|||
|
knows all of the .NET Class Library, not even people that work at Microsoft.
|
|||
|
|
|||
|
Second, necessity will drive you to what you need. Most people go to the
|
|||
|
library when they need to find a book, not to see how many different books
|
|||
|
they can find. You don't need to research classes and methods without a reason.
|
|||
|
When you have trouble figuring out a programming task, you can use your
|
|||
|
favorite search engine to find blog posts, articles, or forums where other
|
|||
|
developers have worked through similar issues. Third-party sources can give
|
|||
|
you clues about which .NET classes and methods you might want to use, and you
|
|||
|
may even find sample code that you can try.
|
|||
|
|
|||
|
Third, Microsoft provides an online language reference and programming guide
|
|||
|
for C# that you can search through. You'll likely spend time reading Microsoft's
|
|||
|
documentation when you need to understand exactly what methods do, how they
|
|||
|
work, and their limitations. This documentation will become your source of
|
|||
|
truth for the .NET Class Library. Microsoft's documentation team works closely
|
|||
|
with the .NET Class Library's software developers to ensure its accuracy.
|
|||
|
|
|||
|
Finally, as you begin to experiment with small code projects you'll deepen
|
|||
|
your understanding of how the classes and methods work.
|
|||
|
|
|||
|
All software developers follow a similar process when stepping into unfamiliar
|
|||
|
territory. The process of discovery is enjoyable, albeit challenging.
|
|||
|
|
|||
|
### Recap
|
|||
|
|
|||
|
The .NET Class Library supplies you with a wealth of functionality that you
|
|||
|
can use by merely referencing the classes and methods that you need.
|
|||
|
Even your data types are part of the .NET Class Library. C# merely provides an
|
|||
|
alias for those data types.
|
|||
|
|
|||
|
---
|
|||
|
|
|||
|
## Exercise
|
|||
|
|
|||
|
### Call the methods of a .NET Class
|
|||
|
|
|||
|
Whether you realized it or not, you've been calling C# methods ever since your
|
|||
|
first "Hello, World!" application. That application uses the `WriteLine()`
|
|||
|
method of the Console class to display the "Hello, World!" message.
|
|||
|
|
|||
|
However, not all classes and methods are implemented the same way. This unit
|
|||
|
covers some of the most common variants that you'll need to understand when
|
|||
|
using methods from the .NET Class Library. More importantly, you'll learn how
|
|||
|
to find and use the documentation to better understand more about each method.
|
|||
|
|
|||
|
### How to call methods in the .NET Class Library
|
|||
|
|
|||
|
From your previous experience with the `Console.WriteLine()` method, you
|
|||
|
should already know the basics:
|
|||
|
|
|||
|
- Start by typing the class name. In this case, the class name is Console.
|
|||
|
- Add the member access operator, the . symbol.
|
|||
|
- Add the method's name. In this case, the method's name is WriteLine.
|
|||
|
- Add the method invocation operator, which is a set of parentheses ().
|
|||
|
- Finally, specify the arguments that are passed to the method, if there are
|
|||
|
any, between the parentheses of the method invocation operator. In this case,
|
|||
|
you specify the text that you want the `Console.WriteLine()` method to write to
|
|||
|
the console (for example, "Hello World!").
|
|||
|
|
|||
|
Optionally, depending on how the developers designed and implemented the given method, you may also need to:
|
|||
|
|
|||
|
- Pass additional values as input parameters.
|
|||
|
- Accept a return value.
|
|||
|
|
|||
|
In the next unit, you'll examine how to pass input values to a method, and how
|
|||
|
a method can be used to return a value to the calling routine.
|
|||
|
|
|||
|
While some methods can be called the same way that you called
|
|||
|
`Console.WriteLine()`, there are other methods in the .NET Class Library that
|
|||
|
require a different approach.
|
|||
|
|
|||
|
### Prepare your coding environment
|
|||
|
|
|||
|
This module includes coding activities that guide you through the process of
|
|||
|
building and running sample code. You are encouraged to complete these
|
|||
|
activities using Visual Studio Code as your development environment. Using
|
|||
|
Visual Studio Code for these activities will help you to become more
|
|||
|
comfortable writing and running code in a developer environment that's used by
|
|||
|
professionals worldwide.
|
|||
|
|
|||
|
1. Open Visual Studio Code.
|
|||
|
2. On the Visual Studio Code File menu, select Open Folder.
|
|||
|
3. In the Open Folder dialog, navigate to the Windows Desktop folder.
|
|||
|
4. In the Open Folder dialog, select Select Folder.
|
|||
|
5. On the Visual Studio Code Terminal menu, select New Terminal.
|
|||
|
6. At the Terminal command prompt, to create a new console application in a
|
|||
|
specified folder, type `dotnet new console -o ./CsharpProjects/TestProject`
|
|||
|
and then press Enter. (`dotnet new console -n PROJECT_NAME`)
|
|||
|
|
|||
|
This .NET CLI command uses a .NET program template to create a new C# console
|
|||
|
application project in the specified folder location. The command creates the
|
|||
|
`CsharpProjects/` and `TestProject/` folders for you, and uses TestProject as
|
|||
|
the name of your `.csproj` file.
|
|||
|
|
|||
|
7. In the EXPLORER panel, expand the `CsharpProjects/` folder. Then select
|
|||
|
`Program.cs`.
|
|||
|
|
|||
|
8. Delete the existing code lines.
|
|||
|
|
|||
|
9. Close the Terminal panel.
|
|||
|
|
|||
|
### Call different kinds of methods in the .NET Class Library
|
|||
|
|
|||
|
In the Visual Studio Code Editor, to create a code sample that implements
|
|||
|
methods of the System.Random and System.Console classes, enter the following
|
|||
|
code:
|
|||
|
|
|||
|
```cs
|
|||
|
Random dice = new Random();
|
|||
|
int roll = dice.Next(1, 7);
|
|||
|
Console.WriteLine(roll);
|
|||
|
```
|
|||
|
|
|||
|
This code simulates a dice roll using the `Random.Next()` method to generate a
|
|||
|
number, and the `Console.WriteLine()` method to display the value.
|
|||
|
|
|||
|
> Note
|
|||
|
> You will examine the code in detail later in this unit.
|
|||
|
|
|||
|
On the Visual Studio Code File menu, click Save.
|
|||
|
|
|||
|
In the EXPLORER panel, to open a Terminal at your TestProject folder location,
|
|||
|
right-click TestProject, and then select Open in Integrated Terminal.
|
|||
|
|
|||
|
Notice that the Terminal panel includes a command prompt that displays a
|
|||
|
folder path. For example:
|
|||
|
|
|||
|
`C:\Users\someuser\Desktop\CsharpProjects\TestProject>`
|
|||
|
|
|||
|
When you use the Terminal to run .NET CLI commands, this folder location is
|
|||
|
where the commands run. Ensure that your code folder matches the folder path
|
|||
|
displayed in the command prompt before you build or run your code.
|
|||
|
|
|||
|
At the Terminal command prompt, to run your code, type dotnet run and then
|
|||
|
press Enter.
|
|||
|
|
|||
|
Notice that a number from 1 to 6 is displayed in the console output (the
|
|||
|
number of dots on the dice). If you run the code enough times, you will
|
|||
|
eventually see each of the numbers displayed.
|
|||
|
|
|||
|
Take a minute to examine the syntax used to access the `Next()` and
|
|||
|
`WriteLine()` methods.
|
|||
|
|
|||
|
Notice that you use different techniques to access the methods.
|
|||
|
|
|||
|
```cs
|
|||
|
Random dice = new Random();
|
|||
|
int roll = dice.Next(1, 7);
|
|||
|
Console.WriteLine(roll);
|
|||
|
```
|
|||
|
|
|||
|
On the third code line, you include a reference to the Console class and call
|
|||
|
the `Console.WriteLine()` method directly. However, you use a different
|
|||
|
technique for calling the `Random.Next()` method. The reason why you're using
|
|||
|
two different techniques is because some methods are "stateful" and others are
|
|||
|
"stateless". You examine the difference between stateful and stateless methods
|
|||
|
in the next section.
|
|||
|
|
|||
|
#### Stateful versus stateless methods
|
|||
|
|
|||
|
In software development projects, the term state is used to describe the
|
|||
|
condition of the execution environment at a specific moment in time. As your
|
|||
|
code executes line by line, values are stored in variables. At any moment
|
|||
|
during execution, the current state of the application is the collection of
|
|||
|
all values stored in memory.
|
|||
|
|
|||
|
Some methods don't rely on the current state of the application to work
|
|||
|
properly. In other words, stateless methods are implemented so that they can
|
|||
|
work without referencing or changing any values already stored in memory.
|
|||
|
Stateless methods are also known as static methods.
|
|||
|
|
|||
|
For example, the `Console.WriteLine()` method doesn't rely on any values
|
|||
|
stored in memory. It performs its function and finishes without impacting the
|
|||
|
state of the application in any way.
|
|||
|
|
|||
|
Other methods, however, must have access to the state of the application to
|
|||
|
work properly. In other words, stateful methods are built in such a way that
|
|||
|
they rely on values stored in memory by previous lines of code that have
|
|||
|
already been executed. Or they modify the state of the application by updating
|
|||
|
values or storing new values in memory. They're also known as instance methods.
|
|||
|
|
|||
|
Stateful (instance) methods keep track of their state in fields, which are
|
|||
|
variables defined on the class. Each new instance of the class gets its own
|
|||
|
copy of those fields in which to store state.
|
|||
|
|
|||
|
A single class can support both stateful and stateless methods. However, when
|
|||
|
you need to call stateful methods, you must first create an instance of the
|
|||
|
class so that the method can access state.
|
|||
|
|
|||
|
### Creating an instance of a class
|
|||
|
|
|||
|
An instance of a class is called an object. To create a new instance of a
|
|||
|
class, you use the new operator. Consider the following line of code that
|
|||
|
creates a new instance of the Random class to create a new object called
|
|||
|
dice:
|
|||
|
|
|||
|
```c
|
|||
|
Random dice = new Random();
|
|||
|
```
|
|||
|
|
|||
|
The `new` operator does several important things:
|
|||
|
|
|||
|
- It first requests an address in the computer's memory large enough to store
|
|||
|
a new object based on the `Random` class.
|
|||
|
- It creates the new object, and stores it at the memory address.
|
|||
|
- It returns the memory address so that it can be saved in the `dice` object.
|
|||
|
|
|||
|
From that point on, when the `dice` object is referenced in code, the .NET
|
|||
|
Runtime performs a lookup behind the scenes to give the illusion that you're
|
|||
|
working directly with the object itself.
|
|||
|
|
|||
|
Your code uses the `dice` object like a variable that stores the state of the
|
|||
|
`Random` class. When you call the `Next()` method on the `dice` object, the
|
|||
|
method uses the state stored in the `dice` object to generate a random number.
|
|||
|
|
|||
|
The latest version of the .NET Runtime enables you to instantiate an object
|
|||
|
without having to repeat the type name (target-typed constructor invocation).
|
|||
|
For example, the following code will create a new instance of the `Random`
|
|||
|
class:
|
|||
|
|
|||
|
```cs
|
|||
|
Random dice = new();
|
|||
|
```
|
|||
|
|
|||
|
The intention is to simplify code readability. You always use parentheses when
|
|||
|
writing a target-typed new expression.
|
|||
|
|
|||
|
### Why is the `Next()` method stateful?
|
|||
|
|
|||
|
You might be wondering why the `Next()` method was implemented as a stateful
|
|||
|
method? Couldn't the .NET Class Library designers figure out a way to generate
|
|||
|
a random number without requiring state? And what exactly is being stored or
|
|||
|
referenced by the `Next()` method?
|
|||
|
|
|||
|
These are fair questions. At a high level, computers are good at following
|
|||
|
specific instructions to create a reliable and repeatable outcome. To create
|
|||
|
the illusion of randomness, the developers of the `Next()` method decided to
|
|||
|
capture the date and time down to the fraction of a millisecond and use that
|
|||
|
to seed an algorithm that produces a different number each time. While not
|
|||
|
entirely random, it suffices for most applications. The state that is captured
|
|||
|
and maintained through the lifetime of the dice object is the seed value. Each
|
|||
|
subsequent call to the `Next()` method is rerunning the algorithm, but ensures
|
|||
|
that the seed changes so that the same value isn't (necessarily) returned.
|
|||
|
|
|||
|
To use the `Random.Next()` method, however, you don't have to understand how
|
|||
|
it works. The important thing to know is that some methods require you to
|
|||
|
create an instance of a class before you call them, while others do not.
|
|||
|
|
|||
|
### How can you determine whether you need to create an instance of a class before calling its methods?
|
|||
|
|
|||
|
One approach for determining whether a method is stateful or stateless is to
|
|||
|
consult the documentation. The documentation includes examples that show
|
|||
|
whether the method must be called from the object instance or directly from
|
|||
|
the class.
|
|||
|
|
|||
|
> Note
|
|||
|
> You may need to scroll down on the documentation page to find the code
|
|||
|
examples.
|
|||
|
|
|||
|
As an alternative to searching through product documentation, you can attempt
|
|||
|
to access the method directly from the class itself. If it works, you know
|
|||
|
that it's a stateless method. The worst that can happen is that you'll get a
|
|||
|
compilation error.
|
|||
|
|
|||
|
Try accessing the `Random.Next()` method directly and see what happens.
|
|||
|
|
|||
|
Enter the following line of code into the Visual Studio Code Editor:
|
|||
|
|
|||
|
```c
|
|||
|
int result = Random.Next();
|
|||
|
```
|
|||
|
|
|||
|
You already know that `Next()` is a stateful method, however this example
|
|||
|
demonstrates how the Visual Studio Code Editor reacts when you try to access a
|
|||
|
method incorrectly.
|
|||
|
|
|||
|
Notice that a red squiggly line appears under `Random.Next`, indicating that
|
|||
|
you have a compilation error.
|
|||
|
|
|||
|
If the method that you're interested in using is stateless, no red squiggly
|
|||
|
line will appear.
|
|||
|
|
|||
|
Hover your mouse pointer over the red squiggly line.
|
|||
|
|
|||
|
A popup window should appear with the following message:
|
|||
|
|
|||
|
Output
|
|||
|

|
|||
|
```txt
|
|||
|
(1,14): error CS0120: An object reference is required for the non-static field, method, or property 'Random.Next()'
|
|||
|
```
|
|||
|
|
|||
|
As you saw in the code at the beginning of the unit, you can fix this error by
|
|||
|
creating an instance of the `Random` class before accessing the `Next()` method.
|
|||
|
|
|||
|
For example:
|
|||
|
|
|||
|
```cs
|
|||
|
Random dice = new Random();
|
|||
|
int roll = dice.Next();
|
|||
|
```
|
|||
|
|
|||
|
In this case, the `Next()` method is called without input parameters.
|
|||
|
|
|||
|
### Recap
|
|||
|
|
|||
|
- To call methods of a class in the .NET Class Library, you use the format
|
|||
|
`ClassName.MethodName()`, where the `.` symbol is the member access operator
|
|||
|
to access a method defined on the class, and the `()` symbols are the method
|
|||
|
invocation operators.
|
|||
|
- When calling a stateless method, you don't need to create a new instance of
|
|||
|
its class first.
|
|||
|
- When calling a stateful method, you need to create an instance of the class,
|
|||
|
and access the method on the object.
|
|||
|
- Use the `new` operator to create a new instance of a class.
|
|||
|
- An instance of a class is called an object.
|
|||
|
|
|||
|
---
|
|||
|
|
|||
|
## Exercise
|
|||
|
|
|||
|
### Return values and parameters of methods
|
|||
|
|
|||
|
In the previous unit, you used a "roll dice" coding scenario to illustrate the
|
|||
|
difference between stateful (instance) and stateless (static) methods. That
|
|||
|
same scenario can help you to understand other important concepts about
|
|||
|
calling methods. For example:
|
|||
|
|
|||
|
- handling the return value of a method.
|
|||
|
- method parameters and passing arguments to a method.
|
|||
|
- choosing an overloaded version of a method.
|
|||
|
|
|||
|
### Return values
|
|||
|
|
|||
|
Some methods are designed to complete their function and end "quietly". In
|
|||
|
other words, they don't return a value when they finish. They are referred to
|
|||
|
as **void methods**.
|
|||
|
|
|||
|
Other methods are designed to return a value upon completion. The return value
|
|||
|
is typically the result of an operation. A return value is the primary way for
|
|||
|
a method to communicate back to the code that calls the method.
|
|||
|
|
|||
|
You saw that the `Random.Next()` method returns an `int` type containing the
|
|||
|
value of the randomly generated number. However, a method can be designed to
|
|||
|
return any data type, even another class. For example, the `String` class has
|
|||
|
some methods that return a string, some that return an integer, and some that
|
|||
|
return a Boolean.
|
|||
|
|
|||
|
When calling a method that returns a value, you'll often assign the return
|
|||
|
value to a variable. That way, you can use the value later in your code. In
|
|||
|
the dice scenario, you assigned the return value of `Random.Next()` to the
|
|||
|
`roll` variable:
|
|||
|
|
|||
|
```cs
|
|||
|
int roll = dice.Next(1, 7);
|
|||
|
```
|
|||
|
|
|||
|
In some cases, you might want to use the return value directly, without
|
|||
|
assigning it to a variable. For example, you might want to print the return
|
|||
|
value to the console as follows:
|
|||
|
|
|||
|
```cs
|
|||
|
Console.WriteLine(dice.Next(1, 7));
|
|||
|
```
|
|||
|
|
|||
|
Even though a method returns a value, it's possible to call the method without
|
|||
|
using the return value. For example, you could ignore the return value by
|
|||
|
calling the method as follows:
|
|||
|
|
|||
|
```cs
|
|||
|
dice.Next(1, 7);
|
|||
|
```
|
|||
|
|
|||
|
However, ignoring the return value would be pointless. The reason you're
|
|||
|
calling the `Next()` method is so that you can retrieve the next random value.
|
|||
|
|
|||
|
### Method parameters and arguments in the calling statement
|
|||
|
|
|||
|
When you call a method, you can pass in values that the method will use to
|
|||
|
complete its task. These values are called arguments. The method uses the
|
|||
|
arguments to assign values to the parameters that are defined in the method's
|
|||
|
signature. A method can require one or more parameters to accomplish its task,
|
|||
|
or none at all.
|
|||
|
|
|||
|
> Note
|
|||
|
> Often times, the terms 'parameter' and 'argument' are used interchangeably.
|
|||
|
However, 'parameter' refers to the variable that's being used inside the method.
|
|||
|
An 'argument' is the value that's passed when the method is called.
|
|||
|
|
|||
|
Most methods are designed to accept one or more parameters. The parameters can
|
|||
|
be used to configure how the method performs its work, or they might be
|
|||
|
operated on directly. For example, the `Random.Next()` method uses parameters
|
|||
|
to configure the upper and lower boundaries of the return value. However, the
|
|||
|
`Console.WriteLine()` uses the parameter directly by printing the value to the
|
|||
|
console.
|
|||
|
|
|||
|
Methods use a method signature to define the number of parameters that the
|
|||
|
method will accept, as well as the data type of each parameter. The coding
|
|||
|
statement that calls the method must adhere the requirements specified by the
|
|||
|
method signature. Some methods provide options for the number and type of
|
|||
|
parameters that the method accepts.
|
|||
|
|
|||
|
When a caller invokes the method, it provides concrete values, called arguments,
|
|||
|
for each parameter. The arguments must be compatible with the parameter type.
|
|||
|
However, the argument name, if one is used in the calling code, doesn't have
|
|||
|
to be the same as the parameter name defined in the method.
|
|||
|
|
|||
|
Consider the following code:
|
|||
|
|
|||
|
```cs
|
|||
|
Random dice = new Random();
|
|||
|
int roll = dice.Next(1, 7);
|
|||
|
Console.WriteLine(roll);
|
|||
|
```
|
|||
|
|
|||
|
The first code line creates an instance of the `Random` class named `dice`.
|
|||
|
The second code line uses the `dice.Next(1, 7)` method to assign a random
|
|||
|
value to an integer named roll. Notice that the calling statement provides two
|
|||
|
arguments separated by a , symbol. The `Next()` method includes a method
|
|||
|
signature that accepts two parameters of type int. These parameters are used
|
|||
|
to configure the lower and upper boundaries for the random number that's
|
|||
|
returned. The final code line uses the `Console.WriteLine()` method to print
|
|||
|
the value of roll to the console.
|
|||
|
|
|||
|
The arguments passed to a method must be the same data type as the
|
|||
|
corresponding parameters defined by the method. If you attempt to pass an
|
|||
|
incorrectly typed argument to a method, the C# compiler will catch your
|
|||
|
mistake and force you to update your calling statement before your code will
|
|||
|
compile and run. Type checking is one way that C# and .NET use to prevent
|
|||
|
end-users from experiencing errors at runtime.
|
|||
|
|
|||
|
> Note
|
|||
|
> Although parameters are often used, not all methods require parameters to
|
|||
|
complete their task. For example, the Console class includes a `Console.Clear()`
|
|||
|
method that doesn't use parameters. Since this method is used to clear any
|
|||
|
information displayed in the console, it doesn't need parameters to complete
|
|||
|
it's task.
|
|||
|
|
|||
|
### Overloaded methods
|
|||
|
|
|||
|
Many methods in the .NET Class Library have overloaded method signatures.
|
|||
|
Among other things, this enables you to call the method with or without
|
|||
|
arguments specified in the calling statement.
|
|||
|
|
|||
|
An overloaded method is defined with multiple method signatures. Overloaded
|
|||
|
methods provide different ways to call the method or provide different types
|
|||
|
of data.
|
|||
|
|
|||
|
In some cases, overloaded versions of a method are used to define a parameter
|
|||
|
using different data types. For example, the `Console.WriteLine()` method has
|
|||
|
19 different overloaded versions. Most of those overloads allow the method to
|
|||
|
accept different types and then write the specified information to the console.
|
|||
|
Consider the following code:
|
|||
|
|
|||
|
```cs
|
|||
|
int number = 7;
|
|||
|
string text = "seven";
|
|||
|
|
|||
|
Console.WriteLine(number);
|
|||
|
Console.WriteLine();
|
|||
|
Console.WriteLine(text);
|
|||
|
```
|
|||
|
|
|||
|
In this example, you're invoking three separate overloaded versions of the
|
|||
|
`WriteLine()` method.
|
|||
|
|
|||
|
- The first `WriteLine()` method uses a method signature that defines an int parameter.
|
|||
|
- The second `WriteLine()` method uses a method signature that defines zero parameters.
|
|||
|
- The third `WriteLine()` method uses a method signature that defines a string parameter.
|
|||
|
|
|||
|
In other cases, overloaded versions of a method define a different number of
|
|||
|
parameters. The alternative parameters can be used to provide more control
|
|||
|
over desired result. For example, the `Random.Next()` method has overloaded
|
|||
|
versions that enable you to set various levels of constraint on the randomly
|
|||
|
generated number.
|
|||
|
|
|||
|
The following exercise calls the `Random.Next()` method to generate random
|
|||
|
integer values with different levels of constraint:
|
|||
|
|
|||
|
1. Ensure that you have an empty Program.cs file open in Visual Studio Code.
|
|||
|
|
|||
|
2. To examine the overloaded versions of the `Random.Next()` method, enter the
|
|||
|
following code:
|
|||
|
|
|||
|
```cs
|
|||
|
Random dice = new Random();
|
|||
|
int roll1 = dice.Next();
|
|||
|
int roll2 = dice.Next(101);
|
|||
|
int roll3 = dice.Next(50, 101);
|
|||
|
|
|||
|
Console.WriteLine($"First roll: {roll1}");
|
|||
|
Console.WriteLine($"Second roll: {roll2}");
|
|||
|
Console.WriteLine($"Third roll: {roll3}");
|
|||
|
```
|
|||
|
|
|||
|
3. On the Visual Studio Code File menu, click Save.
|
|||
|
|
|||
|
4. In the EXPLORER panel, to open a Terminal at your TestProject folder
|
|||
|
location, right-click **TestProject**, and then select **Open in Integrated
|
|||
|
Terminal**.
|
|||
|
|
|||
|
5. At the Terminal command prompt, to run your code, type dotnet run and then
|
|||
|
press Enter.
|
|||
|
|
|||
|
Notice that your result is similar to the following output:
|
|||
|
|
|||
|
Output
|
|||
|
|
|||
|
```txt
|
|||
|
First roll: 342585470
|
|||
|
Second roll: 43
|
|||
|
Third roll: 89
|
|||
|
```
|
|||
|
|
|||
|
The numbers generated are random, so your results will be different. However,
|
|||
|
this example demonstrates the range of results that you might see.
|
|||
|
|
|||
|
6. Take a minute to examine the code.
|
|||
|
|
|||
|
The first version of the `Next()` method doesn't set an upper and lower
|
|||
|
boundary, so the method will return values ranging from `0` to `2,147,483,647`,
|
|||
|
which is the maximum value an int can store.
|
|||
|
|
|||
|
The second version of the `Next()` method specifies the maximum value as an
|
|||
|
upper boundary, so in this case, you can expect a random value between `0` and
|
|||
|
`100`.
|
|||
|
|
|||
|
The third version of the `Next()` method specifies both the minimum and
|
|||
|
maximum values, so in this case, you can expect a random value between `50` and
|
|||
|
`100`.
|
|||
|
|
|||
|
7. Close the Terminal panel.
|
|||
|
|
|||
|
You've already examined several topics in this unit. Here's a quick list of
|
|||
|
what you've covered:
|
|||
|
|
|||
|
- You've examined how to use a method's return value (when the method provides
|
|||
|
a return value).
|
|||
|
- You've examined how a method can use parameters that are defined as specific
|
|||
|
data types.
|
|||
|
- You've examined the overloaded versions of some methods that include
|
|||
|
different parameters or parameter types.
|
|||
|
|
|||
|
### Use IntelliSense
|
|||
|
|
|||
|
Visual Studio Code includes IntelliSense features that are powered by a
|
|||
|
language service. For example, the C# language service provides intelligent
|
|||
|
code completions based on language semantics and an analysis of your source
|
|||
|
code. In this section, you'll use IntelliSense to help you implement the
|
|||
|
`Random.Next()` method.
|
|||
|
|
|||
|
Since IntelliSense is exposed within the code editor, you can learn a lot
|
|||
|
about a method without leaving the coding environment. IntelliSense provides
|
|||
|
hints and reference information in a popup window under the cursor location as
|
|||
|
you enter your code. When you are typing code, the IntelliSense popup window
|
|||
|
will change its contents depending on the context.
|
|||
|
|
|||
|
For example, as you enter the word `dice` slowly, IntelliSense will show all C#
|
|||
|
keywords, identifiers (or rather, variable names in the code), and classes in
|
|||
|
the .NET Class Library that match the letters being entered. Autocomplete
|
|||
|
features of the code editor can be used to finish typing the word that is the
|
|||
|
top match in the IntelliSense popup. Try it out.
|
|||
|
|
|||
|
Ensure that you have your Program.cs file open in Visual Studio Code.
|
|||
|
|
|||
|
Your app should contain the following code:
|
|||
|
|
|||
|
```cs
|
|||
|
Random dice = new Random();
|
|||
|
int roll1 = dice.Next();
|
|||
|
int roll2 = dice.Next(101);
|
|||
|
int roll3 = dice.Next(50, 101);
|
|||
|
|
|||
|
Console.WriteLine($"First roll: {roll1}");
|
|||
|
Console.WriteLine($"Second roll: {roll2}");
|
|||
|
Console.WriteLine($"Third roll: {roll3}");
|
|||
|
```
|
|||
|
|
|||
|
At the bottom of your code file, to experiment with IntelliSense, slowly enter
|
|||
|
the letters `d`, `i` then `c`.
|
|||
|
|
|||
|
Notice the IntelliSense popup window that appears when you begin typing.
|
|||
|
|
|||
|
When IntelliSense pops up, a list of suggestions should appear. By the time
|
|||
|
you have entered `dic`, the identifier `dice` should be at the top of the list.
|
|||
|
|
|||
|
Press the Tab key on the keyboard.
|
|||
|
|
|||
|
Notice that the entire word `dice` is completed in the editor. You can use the
|
|||
|
up and down arrow keys to change the selection before pressing the Tab key.
|
|||
|
|
|||
|
> Note
|
|||
|
> If the IntelliSense window disappears, it can be selected by using the
|
|||
|
backspace key on the keyboard, then re-enter the last symbol to re-open
|
|||
|
IntelliSense.
|
|||
|
|
|||
|
To specify the member access operator, enter a `.` character.
|
|||
|
|
|||
|
Notice that the IntelliSense popup reappears when you enter `.` and shows an
|
|||
|
unfiltered list of all the methods (and other members of the class) that are
|
|||
|
available.
|
|||
|
|
|||
|
Enter N
|
|||
|
|
|||
|
The list will be filtered, and the word Next should be the top selection.
|
|||
|
|
|||
|
To autocomplete the entire word, press the Tab key.
|
|||
|
|
|||
|
To specify the method invocation operator, enter `(`
|
|||
|
|
|||
|
Notice that the closing parenthesis is automatically added for you.
|
|||
|
|
|||
|
The method invocation operator is the set of parentheses located to the right
|
|||
|
of the method name. This portion of the calling statement is where you specify
|
|||
|
the arguments that will be passed to the method. The method invocation
|
|||
|
operator is required when calling the method.
|
|||
|
|
|||
|
Notice that the IntelliSense popup now displays detailed information about the
|
|||
|
`Random.Next()` method.
|
|||
|
|
|||
|
Take a minute to examine the IntelliSense popup for the `Random.Next()` method.
|
|||
|
|
|||
|
> Note
|
|||
|
> If the IntelliSense popup closed before you had a chance to examine it,
|
|||
|
delete the invocation operator (), and then enter ( to display the
|
|||
|
IntelliSense popup.
|
|||
|
|
|||
|
Notice that the popup window includes three sections, one on the left and two
|
|||
|
on the right.
|
|||
|
|
|||
|
On the right side, you should see int `Random.Next(int minValue, int maxValue)`
|
|||
|
in the top section, and ***Returns a non-negative random integer***. in the
|
|||
|
bottom section. The `int` defines the return type for the method. In other words,
|
|||
|
when this version of the method is executed, it will return a value of type `int`.
|
|||
|
|
|||
|
On the left side of the IntelliSense popup, it displays `1/3`.
|
|||
|
|
|||
|
The `1/3` indicates that you're looking at the first of three method
|
|||
|
signatures for the `Next()` method. Notice that this version of the method
|
|||
|
signature enables the method to work with no parameters (no arguments passed
|
|||
|
to the method in the calling statement).
|
|||
|
|
|||
|
Notice that there's also a tiny arrow above and below the `1/3`.
|
|||
|
|
|||
|
To examine the second overloaded version of the method, press the Down Arrow
|
|||
|
key on the keyboard.
|
|||
|
|
|||
|
Notice that you can use the up and down arrow keys to navigate between the
|
|||
|
various overloaded versions. When you do, you'll see the `1/3`, `2/3`, and `3/3`
|
|||
|
appear on the left side of the IntelliSense popup, and helpful explanations on
|
|||
|
the right.
|
|||
|
|
|||
|
Take a minute to examine each of the overloaded versions for the `Random.Next()`
|
|||
|
method.
|
|||
|
|
|||
|
The second overloaded version of the method, `2/3`, informs you that the `Next()`
|
|||
|
method can accept a parameter int maxValue. The description tells you that
|
|||
|
maxValue is the exclusive upper bound for the number that you want the `Next()`
|
|||
|
method to generate. Exclusive indicates that the return number will be less
|
|||
|
than `maxValue`. So when you specify `dice.Next(1,7)`; the max dice roll will
|
|||
|
be 6. Notice that the message at the bottom of the section has been updated to:
|
|||
|
***Returns a non-negative random integer that is less than the specified
|
|||
|
maximum***.
|
|||
|
|
|||
|
The third version of the method, `3/3`, informs you that the `Next()` method
|
|||
|
can accept both int minValue and int `maxValue` as parameters. The new
|
|||
|
parameter, `minValue`, is a lower bound for the number that you want the
|
|||
|
`Next()` method to generate. Since the lower bound is inclusive rather than
|
|||
|
exclusive, the return value can be equal to `minValue`. The message at the
|
|||
|
bottom now states: ***Returns a random integer that is within a specified
|
|||
|
range***.
|
|||
|
|
|||
|
In this case, IntelliSense provides all of the information that you need to
|
|||
|
select the appropriate overload, including a detailed explanation of `maxValue`
|
|||
|
and `minValue`. However, you might encounter situations where you need to
|
|||
|
consult the method's documentation.
|
|||
|
|
|||
|
### Use learn.microsoft.com for information about overloaded methods
|
|||
|
|
|||
|
The second way to learn about overloaded versions of the methods is to consult
|
|||
|
the documentation for the method. The documentation will also help you to
|
|||
|
understand exactly what each parameter is intended for.
|
|||
|
|
|||
|
To begin, open your preferred Web browser and search engine.
|
|||
|
|
|||
|
Perform a search for C# `Random.Next()`
|
|||
|
|
|||
|
Your search should include the class name and method name. You might also want
|
|||
|
to include the term C# to make sure not to accidentally get results for other
|
|||
|
programming languages.
|
|||
|
|
|||
|
Select the top search result with a URL that begins with
|
|||
|
https://learn.microsoft.com.
|
|||
|
|
|||
|
One of the top search results should lead to a URL that begins with
|
|||
|
https://learn.microsoft.com.
|
|||
|
In this case, the link's title should appear as **Random.Next Method**.
|
|||
|
|
|||
|
Here's the link in case you have a problem finding it using a search engine:
|
|||
|
|
|||
|
[Random.Next Method](https://learn.microsoft.com/en-us/dotnet/api/system.random.next)
|
|||
|
|
|||
|
Open the link for C# Random.Next().
|
|||
|
|
|||
|
Quickly scan through the documentation.
|
|||
|
|
|||
|
Scroll down through the page contents to see the various code samples. Notice
|
|||
|
that you can run the samples in the browser window.
|
|||
|
|
|||
|
The learn.microsoft.com documentation follows a standard format for each class
|
|||
|
and method in the .NET Class Library.
|
|||
|
|
|||
|
Near the top of the web page, locate the section labeled Overloads.
|
|||
|
|
|||
|
Notice that there are three overloaded versions of the method listed. Each
|
|||
|
overloaded version that's listed includes a hyperlink to a location further
|
|||
|
down on the page.
|
|||
|
|
|||
|
To navigate "on-page" to a description of the second overloaded version,
|
|||
|
select **Next(Int32)**.
|
|||
|
|
|||
|
Documentation for each version of the method includes:
|
|||
|
|
|||
|
- Brief description of the method's functionality
|
|||
|
- Method's definition
|
|||
|
- Parameters that the method accepts
|
|||
|
- Return values
|
|||
|
- Exceptions that can be raised
|
|||
|
- Examples of the method in use
|
|||
|
- Other remarks about the method
|
|||
|
|
|||
|
Take a minute to review the **Parameters** section.
|
|||
|
|
|||
|
In the Parameters section, you can read that the `maxValue` parameter is the
|
|||
|
"exclusive upper bound of the random number to be generated." An exclusive
|
|||
|
upper bound means that if you want numbers no larger than `10`, you must pass
|
|||
|
in the value `11`.
|
|||
|
|
|||
|
You can also read in the next line: "`maxValue` must be greater than or equal to
|
|||
|
`0`." What happens if you ignore this statement? You can see in the Exceptions
|
|||
|
section that the method will return an `ArgumentOutOfRangeException` when
|
|||
|
`maxValue` is less than `0`.
|
|||
|
|
|||
|
> Note
|
|||
|
> The content at learn.microsoft.com is the "source of truth" for the .NET
|
|||
|
Class Library. It's important to take the time to read the documentation to
|
|||
|
understand how a given method will work.
|
|||
|
|
|||
|
### Recap
|
|||
|
|
|||
|
- Methods might accept no parameters or multiple parameters, depending on how
|
|||
|
they were designed and implemented. When passing in multiple parameters,
|
|||
|
separate them with a `,` symbol.
|
|||
|
- Methods might return a value when they complete their task, or they might
|
|||
|
return nothing (void).
|
|||
|
- Overloaded methods support several implementations of the method, each with
|
|||
|
a unique method signature (the number of parameters and the data type of each
|
|||
|
parameter).
|
|||
|
- IntelliSense can help write code more quickly. It provides a quick reference
|
|||
|
to methods, their return values, their overloaded versions, and the types of
|
|||
|
their parameters.
|
|||
|
- learn.microsoft.com is the "source of truth" when you want to learn how
|
|||
|
methods in the .NET Class Library work.
|
|||
|
|
|||
|
---
|
|||
|
|
|||
|
## Exercise
|
|||
|
|
|||
|
### Complete a challenge activity to discover and implement a method call
|
|||
|
|
|||
|
Code challenges will reinforce what you've learned and help you gain some
|
|||
|
confidence before continuing on.
|
|||
|
|
|||
|
### Math class methods challenge
|
|||
|
|
|||
|
In this challenge, you'll use either Intellisense or learn.microsoft.com to
|
|||
|
find and call a method that returns the larger of two numbers.
|
|||
|
|
|||
|
#### Code challenge
|
|||
|
#### Implement a method of the Math class that returns the larger of two numbers
|
|||
|
|
|||
|
Here are your challenge requirements:
|
|||
|
|
|||
|
1. Ensure that you have an empty Program.cs file open in Visual Studio
|
|||
|
Code.
|
|||
|
|
|||
|
2. Enter the following code as the starting point for your challenge.
|
|||
|
|
|||
|
```cs
|
|||
|
int firstValue = 500;
|
|||
|
int secondValue = 600;
|
|||
|
int largerValue;
|
|||
|
|
|||
|
Console.WriteLine(largerValue);
|
|||
|
```
|
|||
|
|
|||
|
> Note
|
|||
|
> Your final solution for this challenge must use this code, and must use the
|
|||
|
`Console.WriteLine(largerValue)`; statement to generate the output.
|
|||
|
|
|||
|
Find a method of the `System.Math` class that returns the larger of two numbers.
|
|||
|
|
|||
|
You can use either Visual Studio Code "Intellisense" or learn.microsoft.com to
|
|||
|
find the method and determine how to call it properly.
|
|||
|
|
|||
|
Use the method that you found to assign a value to the variable named
|
|||
|
`largerValue`.
|
|||
|
|
|||
|
You should be able to pass the two integer values, `firstValue` and
|
|||
|
`secondValue`, to the method that you found. The method should return a value
|
|||
|
of type `int` that represents the larger of the two arguments that you passed it.
|
|||
|
|
|||
|
You can assign the return value to `largerValue` on a new code line or on the
|
|||
|
existing code line that's used to declare `largerValue`.
|
|||
|
|
|||
|
Verify that your application writes the following output:
|
|||
|
|
|||
|
Output
|
|||
|

|
|||
|
```txt
|
|||
|
600
|
|||
|
```
|
|||
|
|
|||
|
Whether you get stuck and need to peek at the solution or you finish
|
|||
|
successfully, continue on to view a solution to this challenge.
|
|||
|
|
|||
|
---
|
|||
|
|
|||
|
## Review the solution to discover and implement a method call challenge activity
|
|||
|
|
|||
|
The following code is one possible solution for the challenge from the
|
|||
|
previous unit.
|
|||
|
|
|||
|
```cs
|
|||
|
int firstValue = 500;
|
|||
|
int secondValue = 600;
|
|||
|
int largerValue;
|
|||
|
largerValue = Math.Max(firstValue, secondValue);
|
|||
|
Console.WriteLine(largerValue);
|
|||
|
```
|
|||
|
|
|||
|
The `Math.Max()` method supports 13 overloaded versions to accept different
|
|||
|
data types. The overloaded version of the `Math.Max()` method that you call
|
|||
|
will accept int as both input parameters, and returns the larger of the two
|
|||
|
values as an int.
|
|||
|
|
|||
|
When you run the code, you should see the following output:
|
|||
|
|
|||
|
```txt
|
|||
|
600
|
|||
|
```
|
|||
|
|
|||
|
---
|
|||
|
|
|||
|
|