© Radek Vystavěl 2017

Radek Vystavěl, C# Programming for Absolute Beginners, https://doi.org/10.1007/978-1-4842-3318-4_5

5. Working with Objects

Radek Vystavěl

(1)Ondřjov, Czech Republic

Variables of type string, int, double, and bool always contain a single value—text, a single number, or a single yes/no value. However, such “atomic” values can be grouped into aggregates that are called objects. A single object can contain multiple values that are called its components or members. Grouping can go so far that an object can contain several other objects inside itself, for example. In this chapter, you are going to learn about objects.

What Time Is It?

The first object you will encounter is a DateTime object containing various components of a single instance of time, such as day, month, year, hour, minute, second, and so on.

Task

You will write a program that displays the current date and time to the user (see Figure 5-1).

A458464_1_En_5_Fig1_HTML.jpg
Figure 5-1 Displaying the current date and time

In this task, you will get know objects of the DateTime type.

Solution

Here is the code:

static void Main(string[] args)
{
    // Variable of DateTime type, at first empty
    DateTime now;


    // Storing of current date and time into our variable
    now = DateTime.Now;


    // Output
    Console.WriteLine("Now is " + now);


    // Waiting for Enter
    Console.ReadLine();
}

What Date Is It Today?

Let’s go further with the DateTime object .

Task

Say you are interested only in today’s date, with the time component excluded (see Figure 5-2).

A458464_1_En_5_Fig2_HTML.jpg
Figure 5-2 Displaying just the date

The difference between today’s date and current time can be substantial in many programs!

Solution

Here is the code:

static void Main(string[] args)
{
    // Variable of DateTime type, at first empty
    DateTime today;


    // Storing of today's date (without time component)
    today = DateTime.Today;


    // Output
    Console.WriteLine("Today is " + today);


    // Waiting for Enter
    Console.ReadLine();
}

Working with Date Components

You might wonder where the mentioned components of an object are. Let’s see the components of the DateTime object. If you append a variable of the DateTime type with a dot, Visual Studio IntelliSense displays all the possible components available.

Task

You will learn about the various components of the DateTime object.

Solution

Here is the code:

static void Main(string[] args)
{
    // Current date and time (using single statement)
    DateTime now = DateTime.Now;


    // Picking up individual components
    int day = now.Day;
    int month = now.Month;
    int year = now.Year;
    int hours = now.Hour;
    int minutes = now.Minute;
    int seconds = now.Second;
    DateTime justDateWithoutTime = now.Date;


    // Output
    Console.WriteLine("Day: " + day);
    Console.WriteLine("Month: " + month);
    Console.WriteLine("Year: " + year);
    Console.WriteLine("Hours: " + hours);
    Console.WriteLine("Minutes: " + minutes);
    Console.WriteLine("Seconds: " + seconds);
    Console.WriteLine("Date component: " + justDateWithoutTime);


    // Formatting output our way
    Console.WriteLine("Our output: " +
        year + ", " + month + "/" + day +
        " " +
        hours + " hours " + minutes + " minutes");


    // Waiting for Enter
    Console.ReadLine();
}

Figure 5-3 shows the components of the DateTime object .

A458464_1_En_5_Fig3_HTML.jpg
Figure 5-3 Components of the DateTime object

Using Namespaces

Well, now that you have met your first object, I should tell you something about namespaces.

Important using

With the last project still open, use two slashes to comment out the first line (using System;) in the Program.cs source code (see Figure 5-4). You can also just delete the line. However, to return to the original version, it is more convenient just to comment the line out.

A458464_1_En_5_Fig4_HTML.jpg
Figure 5-4 Commenting out the first line

Within an instant, a multitude of red waves appear in the source code. When you try to launch your program using the F5 key, it will not launch (see Figure 5-5).

A458464_1_En_5_Fig5_HTML.jpg
Figure 5-5 Getting errors

Just to remind you, always click No in the error dialog that appears.

The Error List pane that appears shows plenty of errors—suddenly Visual Studio “does not know” either DateTime or Console (see Figure 5-6).

A458464_1_En_5_Fig6_HTML.jpg
Figure 5-6 Error List pane

The using line is quite important, isn’t it? I am going to explain why next.

Namespaces

Almost everything in C# belongs to some hierarchically higher unit. In this case, both DateTime and Console belong to the System namespace. If you want to use them, you have to declare the corresponding namespace with a using line at the top of your source code. Otherwise, Visual Studio does not understand them.

Why are there things like namespaces? What do you need them for? Well, there are not an infinite number of names for objects, so you need to specify which one you are using. For example, you do not need to use the DateTime class just from Microsoft; you could program your own DateTime, or you could buy some wonderful DateTime from another programmer. That is why you need a way to distinguish among them. This way is through namespaces.

Every object type belongs to some namespace. For example, the System namespace is “managed” by Microsoft. If I prepared my own DateTime, I might put it in the RadekVystavěl.Books namespace.

Well, maybe no one needs to make their own DateTime, but there are better examples. For example, the TextBox class prepared for text box controls in programs with graphical user interfaces exists in at least four versions from Microsoft.

  • For desktop apps in Windows Forms technology

  • For desktop apps in WPF technology

  • For web apps

  • For so-called Universal (touch-oriented) apps

Each of the text boxes mentioned belongs to a separate namespace.

Without usings

If you now delete the two slashes you used to comment out the using System; line, everything will return to a normal state. However, it might be interesting to see how the program appears with no using at all, which is what you are going to do next.

In your source code, you need to qualify all the occurrences of DateTime and Console with the appropriate namespace, i.e., System. Qualification is technically performed by prepending the namespace to the name being qualified.

//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;


namespace Date_components__without_using_
{
    class Program
    {
        static void Main(string[] args)
        {
            // Current date and time (using single statement)
            System.DateTime now = System.DateTime.Now;


            // Picking up individual components
            int day = now.Day;
            int month = now.Month;
            int year = now.Year;
            int hours = now.Hour;
            int minutes = now.Minute;
            int seconds = now.Second;
            System.DateTime justDateWithoutTime = now.Date;


            // Output
            System.Console.WriteLine("Day: " + day);
            System.Console.WriteLine("Month: " + month);
            System.Console.WriteLine("Year: " + year);
            System.Console.WriteLine("Hours: " + hours);
            System.Console.WriteLine("Minutes: " + minutes);
            System.Console.WriteLine("Seconds: " + seconds);
            System.Console.WriteLine("Date component: " + justDateWithoutTime);


            // Formatting output our way
            System.Console.WriteLine("Our output: " +
                year + ", " + month + "/" + day +
                " " +
                hours + " hours " + minutes + " minutes");


            // Waiting for Enter
            System.Console.ReadLine();
        }
    }
}

It is better with usings , isn’t it?

Using the Environment Object

To conclude the chapter, you will take one more look at the Environment object you already know. It is fruitful to look at things from different perspectives.

Task

The Environment object contains information about a program’s “surroundings” (that is, about the computer and the operating system). You already saw the Environment.NewLine component. Now you are going to learn about more components.

Solution

Here is the code:

static void Main(string[] args)
{
    // Displaying components of Environment object
    Console.WriteLine("Device name: " + Environment.MachineName);
    Console.WriteLine("64-bit system: " + Environment.Is64BitOperatingSystem);
    Console.WriteLine("User name: " + Environment.UserName);


    // Waiting for Enter
    Console.ReadLine();
}

Contrary to the previous program, I have not extracted object components into variables here. I have used them directly just so you could see another possible way of using them.

Summary

In this chapter, you got acquainted with objects, which are essentially conglomerates of several components. Contrary to “atomic” (single-valued) types such as int or string, objects usually contain a number of values.

Specifically, you met the following:

  • The DateTime object, which can be used to retrieve the current date or time.

  • The Environment object, which can be used to retrieve information about a program’s “surroundings” such as computer names or usernames

You also learned the following:

  • The objects can be stored in variables of the appropriate type.

  • An object’s components can be accessed via so-called dot notation. You write the name of an object’s variable and append the dot, and a list of available components pops up thanks to Visual Studio IntelliSense.

  • Each object type belongs to some namespace. To put it simply, namespaces can be viewed as containers of similar object types.

  • An important namespace is the System namespace, which contains basic object types such as DateTime or Console.

  • You indicate you want to use a specific namespace with a using line at the beginning of the source code.

  • If you do not include the appropriate using line, you have to fully qualify the type’s name. This means you prepend the type’s name with the namespace’s name and a dot.

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

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