© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
R. VystavělC# Programming for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-7147-6_6

6. Using Object Actions

Radek Vystavěl1  
(1)
Ondřejov, Czech Republic
 

You already know from the previous chapter that an object is a kind of data conglomerate consisting of several “pieces of data.” You also know that you can access an object’s individual components when you enter the object name, a dot, and the component name. In this chapter, you will find that objects in programming are even more complex. You will learn that besides data components, objects can encapsulate actions that you can perform with the corresponding object. Through several tasks, you will get practice using object actions.

Displaying the Month in Text

This first task will introduce you to actions that you can perform with DateTime objects.

Task

You will write a program that will display the current date with the month presented by text rather than by a number (or, generally, in long form), as shown in Figure 6-1.
../images/458464_2_En_6_Chapter/458464_2_En_6_Fig1_HTML.jpg
Figure 6-1

Displaying the current date with the month presented in text

You can achieve this task using the ToLongDateString action of the DateTime object.

Solution

Here is the code:
static void Main(string[] args)
{
    // Today's date
    DateTime today = DateTime.Today;
    // Output
    Console.WriteLine("Today is " + today.ToLongDateString());
    // Waiting for Enter
    Console.ReadLine();
}

Discussion

Note the following:
  • When you launch some object action in C#, the action name is always appended by parentheses (round brackets), even if there is nothing between them.

  • The parentheses are often not empty but contain a parameter (or parameters), which is some action-specific information. For example, in the case of the Console.WriteLine action, you specify in parentheses what you want to display.

  • The actions you can perform with objects are also called methods.

  • The month name displayed by the ToLongDateString method depends on the operating system language setting.

Displaying Tomorrow

DateTime objects have more actions available than just converting a date into text. Date arithmetic is especially important.

Task

You will write a program that displays tomorrow’s date (see Figure 6-2).
../images/458464_2_En_6_Chapter/458464_2_En_6_Fig2_HTML.jpg
Figure 6-2

Displaying tomorrow’s date

Solution

DateTime objects can perform further interesting actions (methods), such as the following:
  • Using AddDays for date arithmetic

  • Using ToShortDateString for displaying the date in short form

Here is the code:
static void Main(string[] args)
{
    // Today's date
    DateTime today = DateTime.Today;
    // Tomorrow's date
    DateTime tomorrow = today.AddDays(1);
    // Output
    Console.WriteLine("Today is " + today.ToShortDateString() + ".");
    Console.WriteLine("I will start learning on " + tomorrow.ToShortDateString() + ".");
    // Waiting for Enter
    Console.ReadLine();
}

Displaying a Specific Date

Let’s continue with dates and see what a constructor is.

Task

When working with dates, you do not have to always start from today’s date. You can choose some specific date (see Figure 6-3).
../images/458464_2_En_6_Chapter/458464_2_En_6_Fig3_HTML.jpg
Figure 6-3

Starting with a specific date

Solution

You can create a DateTime object initialized with a specific date by calling an object’s constructor. You enter the new word, type the name (i.e., DateTime), and use parentheses with the possible parameters. In this case, the parameters are the year, month, and day.
static void Main(string[] args)
{
    // A specific date
    DateTime overlordDday = new DateTime(1944, 6, 6);
    // Output
    Console.WriteLine("D-Day (Overlord operation): " +
                        overlordDday.ToLongDateString() + ".");
    // Waiting for Enter
    Console.ReadLine();
}

Rolling a Single Die

Enough dates. Now you will learn how to work with chance or randomness.

Task

You will write a program that “throws” a die three times (see Figure 6-4).
../images/458464_2_En_6_Chapter/458464_2_En_6_Fig4_HTML.jpg
Figure 6-4

Rolling a die

Solution

To work with chance, you need a random number generator . In C#, you use the Random object for that purpose.

You first create a Random object by calling its constructor once at the beginning of the program run, and afterward you repeatedly call its method called Next.
static void Main(string[] args)
{
    // Creating random number generator object
    Random randomNumbers = new Random();
    // Repeatedly throwing a die
    int number1 = randomNumbers.Next(1, 6 + 1);
    int number2 = randomNumbers.Next(1, 6 + 1);
    int number3 = randomNumbers.Next(1, 6 + 1);
    // Output
    Console.WriteLine("Thrown numbers: " +
        number1 + ", " +
        number2 + ", " +
        number3);
    // Waiting for Enter
    Console.ReadLine();
}

Note

The Next method (action) requires two parameters in parentheses:
  • The lower bound of the interval of generated numbers

  • The upper bound increased by 1 (I’m sorry, but I was not the one who invented this strangeness)

Rolling Two Dice

Staying with the topic of random numbers, you will now see how to use more than one random number series.

Task

You will write a program that throws a pair of dice three times (see Figure 6-5). I will show you the right way to do this and the wrong way.
../images/458464_2_En_6_Chapter/458464_2_En_6_Fig5_HTML.jpg
Figure 6-5

Rolling dice three times

Solution

The main message of the solution is to use a single random number generator. If you had two of them created practically at the same time, they would usually generate the same numbers! Here is the code:
static void Main(string[] args)
{
    // 1. CORRECT SOLUTION
    // Creating random number generator object
    Random randomNumbers = new Random();
    // Repeatedly throwing two dice
    int correctNumber11 = randomNumbers.Next(1, 6 + 1);
    int correctNumber12 = randomNumbers.Next(1, 6 + 1);
    int correctNumber21 = randomNumbers.Next(1, 6 + 1);
    int correctNumber22 = randomNumbers.Next(1, 6 + 1);
    int correctNumber31 = randomNumbers.Next(1, 6 + 1);
    int correctNumber32 = randomNumbers.Next(1, 6 + 1);
    // Output
    Console.WriteLine("CORRECTLY");
    Console.WriteLine("Thrown couples: " +
        correctNumber11 + "-" + correctNumber12 + ", " +
        correctNumber21 + "-" + correctNumber22 + ", " +
        correctNumber31 + "-" + correctNumber32);
    // 2. INCORRECT SOLUTION
    // Two random number generators
    Random randomNumbers1 = new Random();
    Random randomNumbers2 = new Random();
    // Repeatedly throwing two dice
    int incorrectNumber11 = randomNumbers1.Next(1, 6 + 1);
    int incorrectNumber12 = randomNumbers2.Next(1, 6 + 1);
    int incorrectNumber21 = randomNumbers1.Next(1, 6 + 1);
    int incorrectNumber22 = randomNumbers2.Next(1, 6 + 1);
    int incorrectNumber31 = randomNumbers1.Next(1, 6 + 1);
    int incorrectNumber32 = randomNumbers2.Next(1, 6 + 1);
    // Output
    Console.WriteLine(); // empty line
    Console.WriteLine("INCORRECTLY");
    Console.WriteLine("Thrown couples: " +
        incorrectNumber11 + "-" + incorrectNumber12 + ", " +
        incorrectNumber21 + "-" + incorrectNumber22 + ", " +
        incorrectNumber31 + "-" + incorrectNumber32);
    // Waiting for Enter
    Console.ReadLine();
}

Getting the Path to the Desktop

To conclude the chapter, you will learn about the actions of yet another object.

Task

When you work with files, you might want to create a file on the user’s desktop. However, everybody has their own file system path to the desktop. I will show you how to find that path (see Figure 6-6).
../images/458464_2_En_6_Chapter/458464_2_En_6_Fig6_HTML.jpg
Figure 6-6

Finding the path

Solution

You can use your old friend, the Environment object. Here is the code:
static void Main(string[] args)
{
    // Finding path to the desktop
    string pathToDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    // Output
    Console.WriteLine("Path to your desktop: " + pathToDesktop);
    // Waiting for Enter
    Console.ReadLine();
}

Enumeration

Pay special attention to the way you have specified that you are interested in the desktop. The value of Desktop is one of the values of an enumeration called Environment.SpecialFolder.

Whenever Visual Studio wants you to enter an enumeration’s value, it usually offers you a corresponding enumeration. In this case, when you choose GetFolderPath from IntelliSense and type an open parenthesis afterward, the Environment.SpecialFolder enumeration immediately pops up (see Figure 6-7).
../images/458464_2_En_6_Chapter/458464_2_En_6_Fig7_HTML.jpg
Figure 6-7

Using IntelliSense

Select the offered enumeration by using the Tab key, enter a dot, and then select the Desktop value.

Summary

The main purpose of this chapter was to show you that objects are more complex entities than just conglomerates of data components. Specifically, they frequently contain methods, which are actions you can perform that usually operate on the object’s data.

You got acquainted with various methods of the DateTime, Random, and Environment objects. Specifically, you studied the following:
  • Conversions of dates to text using the ToLongDateString and ToShortDateString methods

  • One of the methods for date arithmetic, namely, AddDays

  • The Next method for producing a single random number within a specified range

  • The GetFolderPath method, which can be used to get the file system path to special folders such as Desktop, Documents, and so on

You also learned about creating objects using constructor calls. You entered the new word, followed by the object type’s name and parentheses. Some constructors, like that of Random objects, require just empty parentheses, while others, like that of DateTime, require you to specify some values (year, month, and day) between the parentheses.

Within the final example, you also found usage of so-called enumerations, which are essentially sets of predefined (enumerated) values. Visual Studio’s IntelliSense is of great help when working with the enumerations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.145.109