Chapter 3: C# Language Fundamentals

Quiz Solutions

Solution to Question 3-1. A statement is a complete C# instruction, and must end in a semicolon (;).

Solution to Question 3-2. A variable of type bool can have one of two values: true or false.

Exercise 2-3.

Figure A-3. Exercise 2-3.

Solution to Question 3-3. C# contains both intrinsic types and user-defined types. Intrinsic types are built-in, and don’t do much other than hold values. User-defined types are much more flexible, and have abilities determined by code you write, as you’ll see later in the book.

Solution to Question 3-4. A float requires four bytes of memory and a double takes eight bytes, and thus a double can represent much larger values with greater precision. The compiler assumes that any number with a decimal component is a double by default. If you want to specify a float, you need to add the suffix f to the value.

Solution to Question 3-5. A variable is a placeholder for a value. A variable must have an identifier (or a name) and a type.

Solution to Question 3-6. In C, if you wish to use a variable of any type (such as passing it as a parameter to a method) you must first assign it a value. You can initialize a variable without assigning it a value, but you can’t use it in any way until it is assigned.

Solution to Question 3-7. The first two statements are fine. The first is just a simple assignment with no conversion. The second line is an implicit conversion—the int is implicitly converted to a long without any trouble. The third statement is a problem, though—you can’t convert a long to an int, and the compiler will say so. To fix this, you need to cast the long to an int, like this:

int newInt = (int) myLong;

Solution to Question 3-8. In a nutshell, you should use a constant for any information that you know won’t change; everything else should be a variable. Specifically:

Your age in years

This should be a variable, because it changes. Unless you’re in kindergarten, age is normally stated as a whole number, and it’s unlikely to be much more than 100, so a short is appropriate here. But in practice, you’d probably use an int, to avoid unnecessary confusion.

The speed of light in meters per second

The speed of light never changes (or so says Einstein, anyway, and we believe him), so you should use a constant. Its speed is about 3 x 108 meters per second, so a float would do nicely here. However, the compiler defaults to a double, which is also fine.

The number of widgets in your warehouse

This number can change (or so you hope), so a constant isn’t appropriate. Depending on the size of a widget, an int is probably your best choice here. Because the number can’t possibly be negative, you could also use a uint, which would give you some breathing room if you happen to have more than 2 billion widgets, but that’s a bit picky.

The amount of money in your bank account

Again, you would hope that this value can change, so you wouldn’t want to use a constant. A float or double would certainly work here, but the best choice is decimal, which .NET provides specifically for monetary transactions where a high degree of precision is required.

The text of the U.S. Declaration of Independence

Because you’re using text, a string is the best choice here. And because you’re talking about a document that cannot change, a constant would be appropriate. If you wanted to parse or manipulate the text in any way, you’d have to create a new string, but that’s a topic for later.

Solution to Question 3-9. You would refer to the constant that represents the wavelength of green light like this:

WavelengthsOfLight.Green

Its value is 5300.

Solution to Question 3-10. A string literal consists of characters enclosed in double quotes.

Exercise Solutions

Solution to Exercise 3-1. We’ll start easy for this project. Write a short program that creates five variables, one of each of the following types: int, float, double, char, and string. Name the variables whatever you like. Initialize the variables with the following values:

  • int: 42

  • float: 98.6

  • double: 12345.6789

  • char: Z

  • string: The quick brown fox jumped over the lazy dogs.

Then output the values to the console.

This exercise isn’t too much different from the examples in the chapter, particularly Example 3-3. The only difference is that here, you’re using a variety of different data types instead of just int, and that the different types have slightly different syntax. Remember to append an f after the value for the float, to put the value for the char in single quotes, and to put the string in double quotes, and you’ll be fine. If you should happen to get any of those wrong, don’t worry; the compiler will provide an error message to let you know where you went wrong.

One solution is shown in Example A-2.

Example A-2. One solution to Exercise 3-1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_3_1
{
  class Exercise
  {
    static void Main(  )
    {
      int myInt = 42;
      float myFloat = 98.6f;
      double myDouble = 12345.6789;
      char myChar = 'Z';
      string myString = "The quick brown fox jumped over the
                         lazy dogs.";
      Console.WriteLine("myInt: {0}, myFloat: {1}, myDouble: {2},
                        myChar: {3}, myString: {4}", myInt, myFloat,
                        myDouble, myChar, myString);
    }
  }
}

The output should look like this (although where the line breaks on your screen depends on the size of your console window):

myInt: 42, myFloat: 98.6, myDouble: 12345.6789, myChar: Z, myString:
The quick brown fox jumped over the lazy dogs.

Solution to Exercise 3-2. As you gain more experience with programming, you’ll frequently find yourself adapting some code that you wrote before, instead of writing a new program from scratch—and there’s no time like the present to start. Modify the program in Exercise 3-1 so that after you’ve output the values of the variables the first time, you change them to the following:

  • int: 25

  • float: 100.3

  • double: 98765.4321

  • char: M

  • string: A quick movement of the enemy will jeopardize six gun boats

Then output the values to the console a second time.

This exercise is only marginally more difficult than the last. The only trick here is to remember that when you change the value of an existing variable, you don’t need to declare the type again. If you do, you’ll get an error. So, the reassignment of the int shouldn’t look like this:

int myInt = 42;

If you do that, the compiler will think you’re trying to create a new variable with the same name as one that already exists, and you’ll get an error. Instead, you just write this:

myInt = 42;

And there you go. Example A-3 shows what the code should look like.

Example A-3. One solution to Exercise 3-2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_3_2
{
  class Exercise
  {
    static void Main(  )
    {
      int myInt = 42;
      float myFloat = 98.6f;
      double myDouble = 12345.6789;
      char myChar = 'Z';
      string myString = "The quick brown fox jumped over the
                         lazy dogs.";
      Console.WriteLine("myInt: {0}, myFloat: {1}, myDouble: {2},
                        myChar: {3}, myString: {4}", myInt, myFloat,
                        myDouble, myChar, myString);

      myInt = 25;
      myFloat = 100.3f;
      myDouble = 98765.4321;
      myChar = 'M';
      myString = "A quick movement of the enemy will jeopardize
                  six gun boats.";
      Console.WriteLine("myInt: {0}, myFloat: {1}, myDouble: {2},
                        myChar: {3}, myString: {4}", myInt, myFloat,
                        myDouble, myChar, myString);
    }
  }
}

The output should look like this (again, the line breaks on your screen depend on the size of your console window):

myInt: 42, myFloat: 98.6, myDouble: 12345.6789, myChar: Z, myString:
The quick brown fox jumped over the lazy dogs.
myInt: 25, myFloat: 100.3, myDouble: 98765.4321, myChar: M, myString:
A quick movement of the enemy will jeopardize six gun boats.

By the way, you can thank Brian’s ninth-grade typing teacher for that second string; it’s another sentence that uses every letter in the alphabet.

Solution to Exercise 3-3. Write a new program to declare a constant double. Call the constant Pi, set its value to 3.14159, and output its value to the screen. Then change the value of Pi to 3.1 and output its value again. What happens when you try to compile this program?

This program is even simpler than the previous one. All you have to do is remember to use the keyword const when you declare the constant. Example A-4 shows the code.

Example A-4. One solution to Exercise 3-3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_3_3
{
    class Exercise
    {
        static void Main(  )
        {
            const double Pi = 3.14159;
            Console.WriteLine("The value of pi is: {0}", Pi);
            Pi = 3.1;
            Console.WriteLine("The value of pi is: {0}", Pi);
        }
    }
}

This program won’t compile, as you probably found out, because you’re trying to assign a value to a constant. Instead, you receive a compiler error that reads, “The left-hand side of an assignment must be a variable, property or indexer.”

You can “fix” the program by commenting out the reassignment line, but that just gives you two identical lines of output. If you really want to change the value of Pi, you’ll either have to edit your code by hand, or not use a constant. So, when you use a constant in your code, you need to be certain that you’ll never want to change it at runtime.

Solution to Exercise 3-4. Write a new program and create a constant enumeration with constants for each month of the year. Give each month the value equal to its numeric place in the calendar, so January is 1, February is 2, and so on. Then output the value for June, with an appropriate message.

For this exercise, you declare an enumeration just as you saw in Example 3-5. This time, though, you fill in the months of the year appropriately. When you write your Writeline( ) statement in Main( ), be sure to use the proper notation to refer to the constant you want (Months.June in this case), and remember to cast Months.June to an int.

Example A-5 shows what the code should look like.

Example A-5. One solution to Exercise 3-4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_3_4
{
    class Exercise
    {
        // declare the enumeration
        enum Months : int
        {
            January = 1,
            February = 2,
            March = 3,
            April = 4,
            May = 5,
            June = 6,
            July = 7,
            August = 8,
            September = 9,
            October = 10,
            November = 11,
            December = 12
         }

        static void Main(string[] args)
        {
            Console.WriteLine("June is month number {0}.",
                              (int) Months.June);
        }
    }
}

And the output should look something like this, depending on what message you inserted:

June is month number 6.
..................Content has been hidden....................

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