This chapter comes from the 33rd edition of the "Secret Guide to Computers & Tricky Living," copyright by Russ Walter. To read the rest of the book, look at www.SecretFun.com.

Visual C#

A Microsoft employee (Anders Hejlsberg) invented a nifty computer language. He called it Cool but changed the name to C# (pronounced “C sharp”), to emphasize it’s higher than an earlier language, called C. (It’s also higher than a C variant called C++.)

C# tries to combine the best features of Visual Basic, Java, C, and C++:

Like Visual Basic, it lets you create windows easily.

Like Java, it uses modern notation for typing lines in programs.

Like C and C++, it runs fast.

C# is also influenced by an older programming language called Pascal. Before inventing C#, Anders Hejlsberg had already invented two famous Pascal versions (Turbo Pascal and Delphi) and a famous Java version (J++); he was an extremely experienced designer when he invented C#. He knew what was wrong with Pascal, Java, C++, and Visual Basic and how to improve them.

Microsoft recommends using Visual Basic to create simple programs but C# to create bigger projects. Microsoft considers Visual Basic and C# to be the most important computer languages to learn.

You already learned Visual Basic. Now let’s tackle C#.

Modern C#, called Visual C#, is part of Visual Studio. Get Visual Studio’s free version, called Visual Studio Community, by copying it from Microsoft’s Website, using the method on page 563 (“Copy the Community”). This chapter assumes you’ve done that, so you have Visual C# 2015.

Visual C# 2015 understands these commands:


C# command                                       Page

catch                        638

char x;                      634

class Program                632

Console.ReadKey();           633

Console.Write("Love");       633

Console.WriteLine("Love");    633

double x;                    634

double x = -27.0;            634

double[] x = new double[3];   636

double[] x = { 81.2, 51.7, 7.9 }; 636

double[,] x = new double[2, 3]; 636

else                         637

if (age < 18)                636

for (int i = 20; i <= 29; ++i) 638

goto yummy;                  638

int x;                       634

int x = 3;                   635

int[] x = new int[3];        636

int[] x = { 81, 52, 207 };    636

int[,] x = new int[2, 3];     636

long x;                      634

MessageBox.Show("Hair mess"); 641

namespace Joymaker           632

private void Form1_Load(…)    641

public Form1()               641

public partial class Form1 : Form 641

return (a + b ) / 2;         640

static int average(int a, int b) 640

static void Main(string[] args) 632

static void x()              639

string x;                    634

string[] x = { "love", "h" }; 636

Text = “I love you”;         641

try                         638

uint x;                      634

ulong x;                     634

using System;                632

while (true)                 637

x = 3;                       634

x();                         639

++x;                         635

--x;                         635

// Zoo program is fishy       639

It also understands these functions:

C# function                     Page

Console.ReadLine() 635

Convert.ToDouble(x) 635

Convert.ToInt32(x) 636

Convert.ToInt64(x) 636

Convert.ToString(x) 641

Convert.ToUInt32(x) 636

Convert.ToUInt64(x) 636

Math.Abs(x)        634

Math.Acos(x)       634

Math.Asin(x)       634

Math.Atan(x)       634

Math.Atan2(y, x)  634

Math.Ceiling(x)   634

Math.Cos(x)     634

Math.Cosh(x)       634

Math.E             634

Math.Exp(y)        634

Math.Floor(x)       634

Math.Log(x)        634

Math.Log(x, b)       634

Math.Log10(x)       634

Math.PI             634

Math.Pow(x, y)       634

Math.Sin(x)        634

Math.Sinh(x)       634

Math.Sqrt(x)       634

Math.Tan(x)        634

Math.Tanh(x)         634

x.CompareTo(“male”) 637

Fun

Here’s how to enjoy programming in C#.

Start Visual Studio

To start using Visual Studio, type “vi” in the Windows 10 Search box (which is next to the Start button) then click
“Visual Studio 2015: Desktop app”.

If you haven’t used Visual Studio before, the computer says “Sign in”. To reply, do this:

Click the “Sign in” button. Type your email address and press Enter. Type your Microsoft account’s password and press Enter. The computer says “We’re preparing for first use”.

You see the Start Page window.

Start a new program

Click “New Project” (which is near the screen’s left edge) then “Visual C#” then “Console Application”.

Double-click in the Name box (which is near the screen’s bottom). Type a name for your project (such as Joymaker). At the end of your typing, press the Enter key.

Type your program

The computer starts typing the program for you. The computer types:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Joymaker

{

    class Program

    {

        static void Main(string[] args)

        {

        }

    }

}


Let’s write a program that makes the computer say “I love you”. To do that, insert 2 extra lines, so the program becomes this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Joymaker

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("I love you");

            Console.ReadKey();              x

        }

    }

}

Here’s how to insert those line:

Click under the word “void”. Press Enter. Type the first inserted line, press Enter, and type the second inserted line.

The computer indents the lines for you, automatically.

You must type a semicolon at the end of each simple line. But there’s no semicolon at the end of a structure line (a line that’s blank or says just “{” or “}” or is immediately above “{”).

Important line The most important line is the one that says:

            Console.WriteLine("I love you");

It makes the computer write “I love you” onto the screen.

Helper line To make Console.WriteLine work properly, you must put this helper line near the program’s bottom, just above the 3 final “}” lines:

            Console.ReadKey();

That makes the computer pause until the human has read the computer’s output and presses a key.

You must put that helper line in every normal program.

Run the program

To run your program, click “Start” (which is at the screen’s top center) or press the F5 key. (If the “F5” is blue or tiny or the computer is new by Microsoft, HP, Lenovo, or Toshiba, that key works just while you hold down the Fn key, which is left of the Space bar.)

If you did everything correctly, you see the console window (which has white letters on a black background and resembles the DOS command-prompt screen). The console window shows the computer’s output. It shows:

I love you

When you finish admiring that output, press the Enter key (or Space bar or any other normal key) or click the console window’s X button.

If you want to run the program again, click “Start” again.

If you want to edit the program, retype the parts you wish then click “Start” again (which makes the computer debug and run the new version).

Final steps

Similar to Visual Basic, so read “Final steps” on page 566, but change “Funmaker” to “Joymaker” if you named your program “Joymaker”.

Multiple lines

Your program can contain several lines. For example, to make the computer say —


I love you

Let's get married

type these lines:

Console.WriteLine("I love you");

Console.WriteLine("Let's get married");

Below them, type the helper line:

Console.ReadKey();

If you say Write instead of WriteLine, the computer won’t press the Enter key at the end of its writing. For example, if you type:

Console.Write("I love you");

Console.WriteLine("Let's get married");

the computer will write “I love you” without pressing Enter, then write “Let’s get married”, so you see this:

I love youLet's get married

 

Math

The computer can do math. For example, this line makes the computer do 4+2:

Console.WriteLine(4 + 2);

It makes the computer write this answer on your screen:

6

If you have 750 apples and buy 12 more, how many apples will you have altogether? This line writes the answer:

Console.WriteLine("You will have " + (750 + 12) + " apples");

That line makes the computer write “You will have ”, then write the answer to 750 + 12 (which is 762), then write “apples”, so you see this:

You will have 762 apples

Like most other languages (such as Basic, JavaScript, Java, and C++), C# lets you use the symbols +, -, *, /, parentheses, decimal points, and e notation.

Types of numbers

C# handles 5 types of numbers well.

One type of number is called an integer (or int). An integer contains no decimal point and no e and is between -2147483648 and 2147483647. For example, -27 and 30000 are ints. Each int consumes 4 bytes (32 bits) of RAM.

An unsigned integer (or uint) resembles an integer but must not have a minus sign, and it can be between 0 and 4294967295. For example, 3000000000 is a uint, though it’s too big to be an int.

A long resembles an integer but can be longer: it can be between -9223372036854775808 and 9223372036854775807. Each long consumes 8 bytes (64 bits) of RAM.

An unsigned long (or ulong) resembles a long but must not have a minus sign, and it can be between 0 and 18446744073709551615.

A double-precision number (or a double) contains a decimal point or an E. For example, -27.0 and 3E4 are doubles. A double can be up to 1.7976931348623158E308, and you can put a minus sign before it. Each double consumes 8 bytes of RAM. If you write a decimal point, put a digit (such as 0) after it.

Writing When Console.WriteLine makes the computer write an answer on your screen, the computer takes this shortcut: to write a double containing many digits after the decimal point, the computer writes just the first 15 significant digits; and if the only digits after the decimal point are zeros, the computer doesn’t bother writing those zeros or the decimal point.

Operations While you’re writing a math problem,
if you include a double (such as 5.0), the computer makes the answer be a double. For example, the answer to 5.0 + 3 is the double 8.0, though the computer doesn’t bother writing the .0 on your screen.

If you feed the computer a problem that involves just ints, the computer tries to make the answer be an int. If the answer’s too big to be an int, the computer gripes. For example, if you write —

Console.WriteLine(3000 * 1000000);

the computer will gripe (because 3000 and 1000000 are both ints but the answer is too big to be an int). You should rewrite the problem to include a double, like this —

Console.WriteLine(3000 * 1000000.0);

or —

Console.WriteLine(3000.0 * 1000000);

or:

Console.WriteLine(3000.0 * 1000000.0)

Then the answer will be a double (3000000000.0), which the computer will write on the screen in this shortcut form:

3000000000

If you feed the computer a math problem whose answer is too big to be a double, the computer will give up and typically say the answer is:

Infinity

The tiniest double that the computer handles well is 1e-308. If you feed the computer a math problem whose answer is tinier than that, the computer will either handle the rightmost digits inaccurately or give up, saying the answer is 0.0.

Dividing ints Since combining ints gives an answer that’s an int, 11 / 4 is this int: 2. So 11 / 4 is not 2.75. If you say —

Console.WriteLine(11 / 4);

the computer will write just:

2

If you want the computer to write 2.75 instead, say you want a double, by putting decimal points in the problem, like this:

Console.WriteLine(11.0 / 4.0);

That makes the computer write:

2.75

Dividing by 0 If you ask the computer to divide by 0, the computer will gripe.

Dividing by 0.0 If you ask the computer to divide by 0.0, the computer will get creative.

For example, if you say —

Console.WriteLine(5.0 / 0.0);

the computer will try to divide 5.0 by 0.0, give up (because you can’t divide by 0), and say the answer is:

Infinity

If you say —

Console.WriteLine(-5.0 / 0.0);

the computer will try to divide -5 by 0, give up (because you can’t divide by 0), and say the answer is:

-Infinity

If you say —

Console.WriteLine(0.0 / 0.0);

the computer will try to divide 0 by 0, give up (because you can’t divide by 0), get confused, and say the answer is —

NaN

which means “Not a Number”.

Advanced math

The computer can do advanced math. For example, it can compute square roots. This line makes the computer print the square root of 9:

Console.WriteLine(Math.Sqrt(9));

The computer will print 3.

Besides Sqrt, you can use other advanced-math functions:

Function                          Traditional notation What to type

square root of x                  Öx                                  Math.Sqrt(x)

x raised to the y power       xy                                   Math.Pow(x, y)

e raised to the y power       ey                                   Math.Exp(y)

pi                                       p                                    Math.PI

e                                        e                                     Math.E

absolute value of x             |x|                                   Math.Abs(x)

round x down, so ends in .0 ëxû                                  Math.Floor(x)

round x up, so ends in .0    éxù                                  Math.Ceiling(x)

logarithm, base 10, of x      log 10 x                           Math.Log10(x)

logarithm, base e, of x        ln x                                Math.Log(x)

logarithm, base b, of x        log b x                             Math.Log(x, b)

sine of x radians                 sin x                               Math.Sin(x)

cosine of x radians             cos x                              Math.Cos(x)

tangent of x radians            tan x                               Math.Tan(x)

arcsine of x, in radians       arcsin x                          Math.Asin(x)

arccosine of x, in radians    arccos x                          Math.Acos(x)

arctangent of x, in radians  arctan x                          Math.Atan(x)

arctangent of y/x, in radians arctan x/y                       Math.Atan2(y, x)

hyperbolic sine of x           sinh x                             Math.Sinh(x)

hyperbolic cosine of x        cosh x                            Math.Cosh(x)

hyperbolic tangent of x      tanh x                             Math.Tanh(x)

 

Variables

Like Basic and other languages, C# lets you use variables. For example, you can say:

n = 3;

A variable’s name can be short (such as n) or long (such as town_population_in_2001). The name can contain letters, digits, and underscores, but not blank spaces. The name must begin with a letter or underscore, not a digit.

Before using a variable, say what type of thing the variable stands for. For example, if n and town_population_in_2001 will stand for numbers that are ints and mortgage_rate will stand for a double, your program should say:

int n, town_population_in_2001;

double mortgage_rate;

If x is a variable, your program should say one these lines:

Line               Meaning

int x;     x is an integer

uint x;    x is an unsigned integer

long x;       x is a long

ulong x;    x is an unsigned long

double x;  x is a double-precision number

char x;    x is a single character, such as ‘A’

string x; x is a string of characters, such as “love”

If n is an integer that starts at 3, you can say —


int n;

n = 3;

but you can combine those two lines into this single line:

int n = 3;

Here’s how to say “n is an integer that starts at 3, and population_in_2001 is an integer that starts at 27000”:

int n = 3, population_in_2001 = 27000;

If you want x to be the string “I love you”, say —

string x;

x = "I love you";

or combine those lines, like this:

string x = "I love you";

Increase

The symbol ++ means “increase”. For example, ++n means “increase n”.

These lines increase n:

int n = 3;

++n;

Console.WriteLine(n);

The n starts at 3 and increases to 4, so the computer prints 4.

Saying ++n gives the same answer as
n = n + 1, but the computer handles ++n faster.

The symbol ++ increases the number by 1, even if the number is a decimal. For example, if x is 17.4 and you say ++x, the x will become 18.4.

Decrease

The opposite of ++ is --. The symbol -- means “decrease”. For example, --n means “decrease n”. Saying --n gives the same answer as n = n - 1 but faster.

Strange short cuts

If you use the following short cuts, your programs will be briefer and run faster.

Instead of saying n = n + 2, say n += 2, which means “n’s increase is 2”. Similarly, instead of saying n = n * 3, say n *= 3, which means “n’s multiplier is 3”.

Instead of saying ++n and then giving another command, say ++n in the middle of the other command. For example, instead of saying —

++n;

j = 7 * n;

say:

j = 7 * ++n;

That’s pronounced: “j is 7 times an increased n”. So if n was 2, saying j = 7 * ++n makes n become 3 and j become 21.

Notice that when you say j = 7 * ++n, the computer increases n before computing j. If you say j = 7 * n++ instead, the computer increases n after computing j; so j = 7 * n++ has the same effect as saying:

j = 7 * n;

++n;

Input a string

These lines make the computer ask for your name:

Console.WriteLine("What is your name?");

string x = Console.ReadLine();

Console.WriteLine("I adore anyone whose name is " + x);

Below them, remember to put the helper line:

Console.ReadKey();

When you run that program (by pressing the F5 key), here’s what happens.…

The top line makes the computer write this question:

What is your name?

The next line makes the string x be the answer you type. For example, if you answer “What is your name?” by typing “Maria” (and then pressing Enter), the computer will read your answer and make string x be what the computer reads; so x will be “Maria”, and the next line will make the computer write:

I adore anyone whose name is Maria

So when you run that program, here’s the whole conversation that occurs between the computer and you:

The computer asks for your name: What is your name?

You type your name:         Maria

Computer praises your name:          I adore anyone whose name is Maria

Just for fun, run that program again and pretend you’re somebody else.…

The computer asks for your name: What is your name?

You type your name:         Bud

Computer praises your name:          I adore anyone whose name is Bud

When the computer asks for your name, if you say something weird, the computer will give you a weird reply.…

The computer asks for your name: What is your name?

You type:              none of your business!

The computer replies:                      I adore anyone whose name is none of your business!

Input a double

To make x be a string that the human inputs, you’ve learned to say this:

string x = Console.ReadLine();

To make x be a double-precision number that the human inputs, say this instead:

double x = Convert.ToDouble(Console.ReadLine());

That’s because Console.ReadLine() considers the human’s input to be a string, and Convert.ToDouble converts that string to a double.

Examples These lines make the computer predict how old a human will be ten years from now:

Console.WriteLine("How old are you?");

double age = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Ten years from now, you’ll be " + (age + 10));

The top line makes the computer ask, “How old are you?” The middle line makes age be the result of converting, to a double-precision number, the human’s input. The bottom line makes the computer write the answer.

For example, if the human is 27 years old, the chat between the computer and the human looks like this:

How old are you?

27

Ten years from now, you'll be 37

If the human is 27.5 years old, the chat can look like this:

How old are you?

27.5

Ten years from now, you'll be 37.5

These lines make the computer convert feet to inches:

Console.WriteLine("How many feet?");

double feet = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("That makes " + (feet * 12) " inches.");


Input an integer

To make x be an integer that the human inputs, say this instead:

int x = Convert.ToInt32(Console.ReadLine());

That’s because Convert.ToInt32 converts a string to a 32-bit integer.

To make x be a special type of integer that the human inputs, say one of these:

uint x = Convert.ToUInt32(Console.ReadLine());

long x = Convert.ToInt64(Console.ReadLine());

ulong x = Convert.ToUInt64(Console.ReadLine());

Arrays

Instead of being just a number, x can be a list of numbers.

Example For example, if you want x to be this list of integers —

{ 81, 52, 207, 19 }

type this:

int[] x = { 81, 52, 207, 19 };

In that line, the symbol “int[]” means “int list”. Notice that when you type the list of numbers, you must put commas between the numbers and put the entire list of numbers in braces, {}. On your keyboard, the “{” symbol is to the right of the P key and requires you to hold down the Shift key.

In x’s list, the starting number (which is 81) is called x0 (which is pronounced “x subscripted by zero” or “x sub 0” or just “x 0”). The next number (which is 52) is called x1 (which is pronounced “x subscripted by one” or “x sub 1” or just “x 1”). The next number is called x2. Then comes x3. So the four numbers in the list are called x0, x1, x2, and x3.

To make the computer say what x2 is, type this line:

Console.WriteLine(x[2]);

That line makes the computer write x2, which is 207, so the computer will write:

207

Altogether, the lines say:

int[] x = { 81, 52, 207, 19 };

Console.WriteLine(x[2]);

The first line says the integer-list x is { 81, 52, 207, 19 }. The second line makes the computer write x2’s number, which is 207.

Jargon Notice this jargon:

In a symbol such as x2, the lowered number (the 2) is called the subscript.

To create a subscript in your subroutine, use brackets. For example, to create x2, type x[2].

A variable having subscripts is called an array. For example, x is an array if there’s an x0, x1, x2, etc.

Different types Instead of having integers, you can have different types. For example, you can say:

double[] x = { 81.2, 51.7, 207.9, 19.5 };

You can even say:

string[] x = { "love", "hate", "peace", "war" };


Uninitialized Instead of typing a line that includes x’s list of numbers, you can type the numbers underneath, if you warn the computer how many numbers will be in the list, like this:

double[] x = new double[3];

x[0] = 200.1;

x[1] = 700.4;

x[2] = 53.2;

Console.WriteLine(x[0] + x[1] + x[2]);

The top line says x will be a new list of 3 doubles, called x0, x1, and x2. The next lines say x0 is 200.1, x1 is 700.4, and x2 is 53.2. The bottom line makes the computer say their sum:

953.7

Tables If you want x to be a table having 2 rows and 3 columns of double-precision numbers, say:

    double[,] x = new double[2, 3];

Since C# always starts counting at 0 (not 1), the number in the table’s top left corner is called x[0, 0].

 

Logic

Like most computer languages, C# lets you say “if”, “while”, “for”, and “goto” and create comments and subroutines. Here’s how.…

If

If a person’s age is less than 18, let’s make the computer say “You are still a minor.” Here’s the fundamental line:

if (age < 18) Console.WriteLine("You are still a minor.");

Notice you must put parentheses after the word “if”.

If a person’s age is less than 18, let’s make the computer say “You are still a minor.” and also say “Ah, the joys of youth!” and “I wish I could be as young as you!” Here’s how to say all that:

    if (age < 18)

    {

        cout <<"You are still a minor.\n";

        cout <<"Ah, the joys of youth!\n";

        cout <<"I wish I could be as young as you!";

    }

Since that “if” line is above the “{”, the “if” line is a structure line and does not end in a semicolon.

How to type To type the symbol “{”, do this: while holding down the Shift key, tap the “[” key (which is next to the P key). To type the symbol “}”, do this: while holding down the Shift key, tap the “]” key.

When you type a line, don’t worry about indenting it: when you finish typing the line (and press Enter), the computer will indent it the correct amount, automatically.


 

Complete program Here’s how to put that structure into a complete program:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Joan

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("How old are you?");

            double age=Convert.ToDouble(Console.ReadLine());

            if (age < 18)

            {

                Console.WriteLine("You are still a minor.");

                Console.WriteLine("Ah, the joys of youth.");

                Console.WriteLine("I wish I could be as young as you!");

            }

            else

            {

                Console.WriteLine("You are an adult.");

                Console.WriteLine("Now we can have some adult fun!");

            }

            Console.WriteLine("Glad to have met you.");

            Console.ReadKey();

        }

    }

}

If the person’s age is less than 18, the computer will write “You are still a minor.” and “Ah, the joys of youth!” and “I wish I could be as young as you!” If the person’s age is not less than 18, the computer will write “You are an adult.” and “Now we can have some adult fun!” Regardless of the person’s age, the computer will end the conversation by writing “Glad to have met you.”

Since the computer types the top lines for you and also types the 3 braces at the program’s bottom, you type just the lines in the middle, starting with:

            Console.WriteLine("How old are you?");

Fancy “if” The “if” statement uses this notation:

Notation                                                   Meaning

if (age < 18)                if age is less than 18

if (age <= 18)               if age is less than or equal to 18

if (age == 18)               if age is equal to 18

if (age != 18)               if age is not equal to 18

if (age < 18 && weight > 200) if age < 18 and weight > 200

if (age < 18 || weight > 200) if age < 18 or weight > 200

if (sex == "male")           if sex is “male”

if (sex.CompareTo("male") < 0) if sex is a word (such as
                                                                   “female”) that comes before
                                                                   “male” in the dictionary

Here’s how to type the symbol “|”: while holding down the Shift key, tap the “\” key.

Look at that table carefully! Notice that in the “if” statement, you should use double symbols: you should say “==” instead of “=”, say “&&” instead of “&”, and say “||” instead of “|”.

If you accidentally say “=” instead of “==”, the computer will gripe. If you accidentally say “&” instead of “&&” or say “|” instead of “||”, the computer will say right answers but too slowly.


The symbol “<” compares just numbers, not strings. Instead of writing —

if (sex < "male")

you must write:

if (sex.CompareTo("male") < 0)

While

Let’s make the computer write the word “love” repeatedly, like this:

love love love love love love love love love etc.

love love love love love love love love love etc.

love love love love love love love love love etc.

etc.

This line does it:

while (true) Console.Write("love ");

The “while (1)” means: do repeatedly. The computer will do cout <<“love ” repeatedly, looping forever — or until you abort the program (by clicking the console window’s X button).

Let’s make the computer start at 20 and keep counting, so the computer will write:

20

21

22

23

24

25

26

27

28

29

30

31

32

etc.

These lines do it:

Program                                               Meaning

int i = 20;                  Start the integer i at 20.

while (true)             Repeat these lines forever:

{

    Console.WriteLine(i);     print i then press Enter

    ++i;                   increase i

}

They write faster than you can read.

To pause the writing, press the Pause key.

To resume the writing, press the Enter key.

To abort the program, click the console window’s X button.

In that program, if you say “while (i < 30)” instead of “while (true)”, the computer will do the loop just while i remains less than 30; the computer will write just:

20

21

22

23

24

25

26

27

28

29


 

To let that program run properly, make sure its bottom includes the helper line saying “Console.ReadKey()”, so altogether the program looks like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Joan

{

    class Program

    {

        static void Main(string[] args)

        {

            int i=20;

            while (i < 30)

            {

                Console.WriteLine(i);

                ++i;

            }

            Console.ReadKey();

        }

    }

}

Instead of saying “while (i < 30)”, you can say “while (i <= 29)”.

For

Here’s a more natural way to get that output of numbers from 20 to 29:

for (int i = 20; i <= 29; ++i) Console.WriteLine(i);

The “for (int i = 20; i <= 29; ++i)” means:

Do repeatedly. Start the integer i at 20, and keep repeating as long as i <= 29. At the end of each repetition, do ++i.

In that “for” statement, if you change the “++i” to “i += 3”, the computer will increase i by 3 instead of by 1, so the computer will write:

20

23

26

29

The “for” statement is quite flexible. You can even say “for (int i = 20; i < 100; i *= 2)”, which makes i start at 20 and keep doubling, so the computer writes:

20

40

80

Like “if” and “while”, the “for” statement can sit atop a group of indented lines that are in braces.


Goto

You can say “goto”. For example, if you say “goto yummy”, the computer will go to the line whose name is yummy:

    Console.WriteLine("my dog ");

    goto yummy;

    Console.WriteLine("never ");

yummy: Console.WriteLine("drinks whiskey");

The computer will write:

my dog

drinks whiskey

Exceptions

These lines try to make x be how many children the human has:

Console.WriteLine("How many children do you have?");

int x = Convert.ToInt32(Console.ReadLine());

Those lines ask the human “How many children do you have?” then wait for the human’s response then try to convert that string to an integer (such as 2 or 0) and call it x. But what happens if the human does not input an integer? What if human inputs a number that includes a decimal point? What if the human types a word, such as “none” or “one” or “many”? What if the human types a phrase, such as “not sure” or “too many” or “none of your business” or “my girlfriend was pregnant but hasn’t told me yet whether she got an abortion”? In those errant situations (which are called exceptions), the computer can’t do Convert.ToInt32 and will instead abort the program, show the human all the program’s lines, and highlight the problematic line. Then the human will be upset and confused!

To avoid upsetting people, change those lines to this group of lines instead:

AskAboutKids:

    Console.WriteLine("How many children do you have?");

try

{

    int x = Convert.ToInt32(Console.ReadLine());

}

catch

{

    Console.WriteLine("Please type an integer");

    go to AskAboutKids;

}

The group begins with a label (AskAboutKids) and makes the computer ask “How many children do you have?” Then the computer will try to do this line:

    int x = Convert.ToInt32(Console.ReadLine());

If the computer fails to do that line (because what the person typed can’t be converted to an integer), the computer won’t gripe; instead, it will catch the error and do the lines indented under “catch”. Those lines are called the catch block (or
exception handler). They make the computer say “Please type an integer” then go back to the beginning of AskAboutKids, to give the human another opportunity to answer the question correctly.

If the human doesn’t know what an “integer” is, phrase the advice differently: make the computer write “Please type a simple number without a decimal point”.


Comments

To put a comment in your program, begin the comment with the symbol //. The computer ignores everything that’s to the right of //. Here’s an example:

// This program is fishy

// It was written by a sick sailor swimming in the sun

Console.WriteLine("Our funny God");   // notice the religious motif

Console.WriteLine("invented cod");    // said by a nasty flounder

The computer ignores all the comments, which are to the right of //.

While you type the program, the computer makes each // and each comment turn green. Then the computer ignores everything that’s turned green, so the computer writes just:

Our funny God

invented cod

Subroutines

Like most other languages, C# lets you invent subroutines and give them names. For example, here’s how to invent a subroutine called “insult” and use it in the Main routine:

Program                                                                                               Meaning

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Joan

{

    class Program

    {

        static void Main(string[] args)                Here’s the main routine:

        {

            Console.WriteLine("We all know...");        write “We all know…”

            insult();                              do the insult

            Console.WriteLine("...and yet we love you."); write the ending

            Console.ReadKey();

        }

        static void insult()                     x      Here’s how to insult:

        {                                        x

            Console.WriteLine("You are stupid!");       write “You are stupid!”

            Console.WriteLine("You are ugly!");  x      write “You are ugly!”

        }                                        x

    }

}

The computer will write:

We all know...

You are stupid!

You are ugly!

...and yet we love you.

In that program, the lines beginning with “static void Main(string[] args)” define the Main routine. The bottom few lines, beginning with “static void insult()”, define the subroutine called “insult”.

Whenever you write a subroutine’s name, you must put parentheses afterwards, like this: insult(). Those parentheses tell the computer: insult’s a subroutine, not a variable.

To write a subroutine’s definition simply, begin the definition by saying “static void”.

Here’s another example of a main routine and subroutine:

Routines                                                                                               Meaning

static void Main(string[] args)                      Here’s the main routine:

{

    laugh();                                      main routine says to laugh

    Console.ReadKey();

}

static void laugh()                                     x Here’s how to laugh:

{                                                       x

    for (int i = 1; i <= 100; ++i) Console.Write("ha ");  write “ha ”, 100 times

}                                                       x

The Main routine says to laugh. The subroutine defines “laugh” to mean: write “ha ” a hundred times.


Let’s create a more flexible subroutine, so that whenever the Main routine says laugh(2), the computer will write “ha ha ”and Enter; whenever the Main routine says laugh(5), the computer will write “ha ha ha ha ha ” and Enter; and so on. Here’s how:

Routines                                                                                   Meaning

static void Main(string[] args)                  Here’s the main routine:

{

    Console.Write ("Here is a short laugh: ");

    laugh(2);                                 do laugh(2), so write “ha ha ”

    Console.Write ("Here is a longer laugh: ");

    laugh(5);                                 do laugh(5), so write “ha ha ha ha ha ”

    Console.ReadKey();

}

static void laugh(int n)                              x Here’s how to laugh(n):

{                                                     x

    for (int i = 1; i <= n; ++i) Console.Write("ha "); write “ha ”, n times

    Console.WriteLine();                              x then press Enter

}                                                     x

The computer will print:

Here is a short laugh: ha ha

Here is a longer laugh: ha ha ha ha ha

Average Let’s define the “average” of a pair of integers, so that “average(3, 7)” means the average of 3 and 7 (which is 5), and so a Main routine saying “i = average(3, 7)” makes i be 5.

This subroutine defines the “average” of all pairs of integers:

static int average(int a, int b)

{

    return (a + b) / 2;

}

The top line says, “Here’s how to find the average of any two integers, a and b, and make the average be an integer.” The next line says, “Return to the main routine, with this answer: (a + b) / 2.”

Here’s a complete program:

Program                                                                            Meaning

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Joan

{

    class Program

    {

        static void Main(string[] args) Here’s the main routine:

        {

            int i;                     make i be an integer

            i = average(3, 7);         make i be average(3, 7)

            Console.WriteLine(i);      write i

            Console.ReadKey();

        }

        static int average(int a, int b)x Here’s how to compute average(a, b):

        {                               x

            return (a + b) / 2;         x return this answer: (a + b) / 2

        }                               x

    }

}

In that program, the Main routine is:

            int i;                     make i be an integer

            i = average(3, 7);         make i be average(3, 7)

            Console.WriteLine(i);      write i

            Console.ReadKey();

You can shorten it, like this:

            int i = average(3, 7);       make the integer i be average(3, 7)

            Console.WriteLine(i);      write i

            Console.ReadKey();

You can shorten it further, like this:

            Console.WriteLine(average(3, 7)); write average(3, 7)

            Console.ReadKey();

To make that program handle double-precision numbers instead of integers, change each int to double. After changing to double, the program will still work, even if you don’t change 3 to 3.0 and don’t change 7 to 7.0.


Windows forms

Like Visual Basic, C# lets you easily create Windows forms. Here’s how.

Start C# (by typing “vi” in the Windows 10 Search box, then clicking “Visual Studio 2015: Desktop app” then “New Project” then “Visual C#”).

Click “Windows Forms Application”.

Double-click in the Name box (which is near the screen’s bottom). Type a name for your project (such as Joymaker). At the end of your typing, press the Enter key.

You see an object, called the Form1 window. Double-click in that window (below “Form1”). That tells the computer you want to write a program (subroutine) about that window.

The computer starts writing the subroutine for you. The computer writes:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace Joymaker

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

 

        }

    }

}

The line saying “private void Form1_Load” is the subroutine’s header. Below that, between the braces (the symbols “{” and “}”), insert lines that tell the computer what to do when Form1 is loaded (appears). The lines you insert are called the subroutine’s body.

Simplest example

Let’s make the Form1 window say “I love you”. To do that, type this line —

        Text = "I love you";

The computer automatically indents that line for you, so the subroutine becomes:

        private void Form1_Load(object sender, EventArgs e)

        {

            Text = "I love you";

        }

To run your program, click “Start” (which is at the screen’s top center). Then you see the Form1 window again; but instead of saying “Form1”, it tries to say the text:

I love you

(To see all that, maximize that Form1 window by clicking its Maximize button, which is left of its X.)

When you’ve finished admiring the Form1 window, stop the program by clicking the Form1 window’s X button. Then you see the subroutine again:

        private void Form1_Load(object sender, EventArgs e)

        {

            Text = "I love you";

        }

If you wish, edit the subroutine. For example, try changing the Text line to this:

            Text = "I hate cabbage";

Math

The Text line can include math calculations, but you must convert the answer to a string, since Text must be a string. For example, to make the computer write the answer to 4 + 2, type this line:

            Text = Convert.ToString(4 + 2);

Message box

To create a message box saying “Your hair is messy”, type this line:

            MessageBox.Show("Your hair is messy");

To create a message box saying the answer to 4 + 2, type this line:

            MessageBox.Show(Convert.ToString(4 + 2));

Property list

Click the “Form1.cs [Design]” tab, so you see the Form1 window itself. Then click (just once) in the middle of the Form1 window.

Then the screen’s bottom-right corner shows a list whose title is:

Properties

Form1 System.Windows.Forms.Form

That list is called Form1’s main property list (or
property window). It looks the same as if you were using Visual Basic. To explore it, reread my chapter about Visual Basic.

See the toolbox

Click the “Form1.vb [Design]” tab then “View” (which is near the screen’s top-left corner) then “Toolbox”. Then you see 10 toolbox categories:

All Windows Forms

Common Controls

Containers

Menus & Toolbas

Data

Components

Printing

Dialogs

WPF Interoperability

General

(If you don’t see that whole list yet, scroll down.)

The toolbox looks the same way as if you were using Visual Basic. To explore how to use its tools, reread pages 576-584, starting with “See common controls”.