Вы находитесь на странице: 1из 104

M at h Com poser 1. 1.

5
ht t p: / / www. m at hcom poser . com

Dear Reader,
This booklet on Microsoft C# 6.0 is only 101 pages, but it's richly illustrated for
improved, and more immediate comprehension. It's one thing to read a book on
coding, but it's quite another to truly understand what the code is doing, or why
it's doing it. Therefore, this first book in the series has a heavy focus on creating
flow diagrams in order to build deeper and more immediate understanding.
There are 34 check point exercises with solutions included. This material is best
read with Visual Studio Community 2015 open and ready to go. It's important
you practice as soon and frequently as possible. Because this book focuses on
doing things that produce results quickly, this book follows the question and
answer format. The answers are stand alone code examples you should type into
Visual Studio. There are also brief discussions where needed, and the code is
heavily annotated with comments, and many flow diagrams. The driving
philosophy of this first book in the series is simple:

Mastery results from a deep understanding of how many small pieces interact
to produce something more complex. There are no long paragraphs in this book.
Partial List Of Topics Covered:

1) How to get Visual Studio Community


2) How to create and run a simple console application to display text
3) How to add a variable, change it, and display its values
4) How to format output
5) How to describe the world with multiple variables, and data types
6) How to read input in various formats
7) How to process input with basic mathematcal operations
8) How to draw flow diagrams to help improve understanding
9) How to code if/else blocks, while loops, for loops, foreach loops
10) How to use the debugger to execute code line by line
11) How to chain and nest methods
12) How to code loops to collect user input forever
13) Logical, compound operators, and the ternary operator
14) Understanding how to use properties
15) Understanding how to create arrays, and how to read them,
and use for loops with arrays
16) Understanding nested arrays, and nested foreach loops
17) Understanding value type and reference type variables
18) Creating and calling methods that operate on numbers and arrays
19) Creating and using methods using the params keyword
20) Creating and using methods using the out and ref keywords
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

21) Creating classes and instance variables


22) Creating instances of classes, and calling instance methods
23) Creating and using traditional and auto-implemented properties
24) Understanding how two classes can be coded in one file
25) Understanding the difference between positional and named arguments
26) Creating and using static fields and properties
27) Understanding why static classes and methods exist
28) Understanding how generic lists make it easier to code
29) Understanding how progammer defined types can be used as method
parameters and fields
30) Creating class hierarchies, and understanding how inheritance helps
write less code
31) Seeing how code with multiple inherited classes executes
32) Visualizing a class hierarchy using the class diagram
33) Understanding how to view inherited fields and properties
34) Understanding how to create and use virtual method in order to centralize
code and logic
35) Understand what polymorphism is, and how exactly it helps to write less
code
At the end of the content is a link to one of my udemy courses with a highly
discounted coupon if you are a person who learns best by watching videos.

The most important sequence of steps in this book is shown below. Use these
with every example, and your comprehension will become very deep and
complete. Ultimately, my friends, this is the only kind of comprehesion that is
worth our time and effort.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.

I am the author of one of the best selling C# courses on udemy. Please visit
udemy.com for more.

www.udemy.com/u/tomaszowsiak

Copyright @2016 by Tom Owsiak


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

1
Question 1: How do I download and install Visual Studio 2015 Community?
Answer 1: Do an Internet search for "visual studio 2015 community".
Doing so should bring you to a page similar to the one below. There should
be a big download button. Click it, and follow the directions as they appear.
Downloading and installing Visual Studio 2015 Community can be a process
that takes time, so patience is in order.

Question 2: How does VS 2015 Community look when launched?


Answer 2: Below is a picture. Yours should look similar.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

2
Question 3: How is "C#" pronounced, and what is it exactly?
Answer 3: In English, we pronounce this as "c sharp". It's a powerful
programming language from Microsoft.
Question 4: How can a simple, understandable program be made in C#?
Answer 4: Launch Visual Studio, and follow the numbered steps below to create
a console application.

1
2 3

You can leave these settings as they are.


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

3
The simple console application program code is shown below. This code has
features that are not needed at first.

Simplify your code by erasing the elements highlighted in the red boxes below.

1. Erase

2. Erase

3. Erase

4. Erase
Only the code shown below should be left at this point.

1." using System;" looks faded because


it has not yet been used.
2. Green line on left means this code
has been changed, and saved.

3. Yellow line on the left means this code has


been changed, but not yet saved.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Question 5: How can the program developed so far be run? 4


Answer 5: Press Ctrl+F5, or follow the numbered arrows below to run it through
the graphical user interface.
1. Begin with this simple code. 2. Left click Debug

3. Click here
4. Get console application

Line numbers

Question 6: What is a comment?


Answer 6: Comments are annotations that make code easier to read. Comment
your code richly so you will not be lost when you look at it later. Comments are
written as //...comment. Below are examples of comments. Read the
comments you see in this book very carefully.

Comments

Question 7: What are curly braces?


Answer 7: Curly braces are used to set off blocks of code. They must always
come in pairs, or the code will not work.

1. These curly braces go together as a pair.

2. These curly braces go together as a pair.


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

5
Question 8: How can a line of text be shown in a console application?
Answer 8: Add line 7, as in the code below. Notice that now "using System;" is
no longer faded. This confirms that Console.WriteLine(..) is accessed by writing
"using System;". WriteLine(..) is a method. This version of it prints a sequence
of characters within double quotes. This is called a "string". End your
statements always with semicolons, or ";". Press Ctrl+F5 to run this new code.

This is the output.

Below is an analysis of the flow of this program.

1. Load main
2. Hit first curly brace to enter main
3. Print string to screen

4. Hit second curly brace

5. Exit

Check point 1: Write another line of code to print "Hello, World!"


Question 9: When writing Console.WriteLine(..), there is a dot between
Console and WriteLine(..). What does this dot mean?
Answer 9: Rewrite the code as shown below. Typing "." steps through from a
name space, to a class, and then to a method inside that class.
Name spaces group related functionality.
1.
"."
2.
"."
Name Class Method 3.
Space
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

6
Check point 1 solution: (Change to code is shown in red box.)

Question 10: It seems that "Console" is something that could occur frequently. Is
a way available of not having to write "Console" many times?
Answer 10: C# has a feature that allows using the "static" keyword together
with a using statement.
1.Put "static System.Console;"

3. Output is still the same as before.

2. Do not use Console here

Question 11: Things change. How are changing quantities written in C#?
Answer 11: C# has variables. Variables are named memory locations where the
value stored usually changes over time. The program below shows how to create
a variable and set its value. Name for memory location Memory location

value
salary 45000
stored

named memory location

data name value


type
C# is strongly typed. This means that a variable has a definite type of data it
can store. The decimal type is good for money because it is accurate, which is
important when dealing with monetary values.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

7
Question 12: Once a variable value is set, how can the variable value be displayed
in a console window?
Answer 12: C# has string interpolation. Put a dollar symbol before the string,
and then place the variable between curly braces inside the string. Here forward,
"curly braces" will be called "curlies".

1. Dollar symbol 2. Variable name


in front of string between curlies
Below is a rough flow analysis to show what actually happens when a variable is
declared, and then set.
1. Begin on curly 2. Declare variable

3. Assign value to variable


Question 13: Once a variable is set, how can its value be changed, and shown?
Answer 13: Write the name of the variable, and assign a new value. Do not write
the data type again. The steps required to assign and print a new value are shown
in the red box below.

Check Point 2: Print "Salary is 65000" in a console window.


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

8
Check point 2 sample solution: (Code changes in red box.)

Question 14: What is the list of suggested features called that shows as code is
typed?
Answer 14: This list is called "IntelliSense". Learn to use it well. It can save a lot
of time, and wasted effort.

"IntelliSense"

Type System and then hit "." on your keyboard. This will show you what is
accessible in the System name space. If you choose Console, and then type a
period, you'll see what is available as a feature inside the Console class.
1. 2. 3.
1. 2.

Question 15: How can more useful information be found about code features ?
Answer 15: Hover your mouse over a bit of code. An editor tool tip should show.
These are useful because they provide a lot of detail.

"void" means WriteLine(..) Location and Data type of Description of


performs a useful action but name of value to be action method
it does not return a value. method operated on can perform
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

9
Question 16: The world is made of many different objects. How can these be
represented in C#?
Answer 16: C# has different data types. Imagine we want to describe a cup. We
look at the cup, and then translate its properties, like whether it has a lid or not,
into data types in C#.
Use decimal for money because
it's accurate. "M" is needed when
putting numbers after the decimal
point in a decimal data type. Use doubles to
represent measured
values, like a height
Use booleans to represent
you can measure
one of only two possible values.
with a ruler.
Either the cup is covered, or it's
not. Only two options are possible.

Use string to represent text, like


the color of the cup.

When deciding on a data type, ask the kinds of questions outlined above.

Check point 3: Write code to describe this rectangle:


width=4.25 (measured with ruler)

height=2.3 (measured with ruler)


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

10
Check point 3 sample solution:

Question 17: How can useful calculations be done in C#?


Answer 17: Imagine last year John had a salary of 45000, and this year his
salary is 55000. Let's find the total and average of his salaries. Use camel casing
to name the variables. As an example, "salaryLastYear" is named
with camel casing because Last and Year are capitalized and look like humps.
totalEarned is a "computed" variable. It's called that because it's the result of a
calculation done on the right side of the equals sign.
data type computedVariable=calculation;

Average salary is total salary divided by 2. The variable "totalEarned" is


usable on the right side because it's set above at comment number 3.
Check point 4: Create a new variable called "ratioOfSalaries", and then divide
this year's salary by last year's salary to compare the two. Use "/" for division.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 4 sample solution: (Code changes are in red box.) 11

Question 18: Can calculations be done inside WriteLine(..)?


Answer 18: Yes. The math is done, and then the results are printed in the string.

multiplication
symbol

Question 19: Why must we be careful with division when working in C#?
Answer 19: The results of division depend on whether we're dividing a type that
can store decimals, or a type that stores only whole numbers. The integer type,
written as "int" in C#, stores numbers like -5,0 and 10. The double type, on the
other hand, stores values like -45.909, 0.02, and 4.556.

Result is another
whole number like 1

Result is another
double like 1.04
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

12
Question 20: What's the difference in using "/" to divide, and "%" to divide?
Answer 20: Imagine you want to find how many whole weeks in a year, and
how many days are left after all the whole weeks are taken out.

The two symbols "/" and "%" do not produce the same results from division.
Question 21: How are complex mathematical expressions evaluated?
Answer 21: The biggest rule is this: enclose anything you want to happen first
inside parenthesis, and then the order of execution is from the inside to the
outside. There are many other smaller rules, of course. Apply the rules of basic
algebra in most cases, and, if needed, rewrite a complex expression as a
sequence of more basic ones, until you feel you truly understand.

1) 2*(4+3*(4/2))
do 4/2
Check point 5: Write code to find the average of 2) 2*(4+3*2)
the three values shown below. Use variables. do 3*2
x=1, y=5, z=6. 3) 2*(4+6)
sum of values do 4+6
The average is defined as 4) 2*10
number of values
do 2*10
5) 20
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

13
Check point 5 sample solution:

Question 22: Many times expressions that change a variable and store back
to the same location need to be used. What are some examples of this?
Answer 22. Compound operators like "+=" can be used to write x+=1 instead of
x=x+1. The two produce equivalent results, but do not look the same.
x=x+1 is the same as x+=1
Both add 1 to x and store back
to x. Follow the arrows below
to see how x changes.

5+1

6-10

-4*3

-12/2

Question 23: What is the difference between writing x++ and ++x?
Answer 23: x++ first uses x, and then adds 1. ++x first adds 1, and then uses x.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

14
Question 24 : The amount of money in a bank account changes over time. The
number of months in a year never changes. It's constant. How are constant
quantities represented and used in C#?
Answer 24: Look at the triangles shown. The side length changes from triangle
to triangle, but the number of sides NEVER changes. Declare number of sides to
be constant. The ushort data type is used because it's small and never negative.

side length=1
sides=3 side length=2
sides=3 side length=3
sides=3

Trying to change a constant after it's set gives an error.


3.45 3.45

3.45
3*3.45=10.35

Check point 6: Below is a series of squares. Look at them carefully.


1) What's constant?
2) What's changing?
3) Write code to find the perimeter of a square.

side length=1 side length=2 side length=3


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

15
Check point 6 sample solution: Every square has four sides
3.45

3.45 3.45

3.45

Question 25: What is variable scope, and how does it work?


Answer 25: Variable scope is the extent to which variables exist. Variables
come into existence, exist, and then cease to exist.
numberOfBlocksRun
exists here

no y

y
exists
here

y ceases
to exist

new y
exists
here

new y
is dead
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

16
Question 26: To make a useful program, input needs to be accepted, and turned
into output. How can this be done in C#?
Answer 26: C# has a method called ReadLine(). Use it to read string input
from users. A way to make a method act on a variable is to use the following
syntax: "name of variable.name of method()". Example: input.ToUpper()

Data types on left and rights sides


of "=" should match to avoid errors.

same

Question 27: How can numerical input be collected, processed, and output?
Answer 27: Collecting numerical input requires a data conversion. Another
way to make a method act on a variable is to pass the variable to the method
using this syntax: MethodName(variable name).
Example: double.Parse(input) means attempt to convert "input" to numerical
form. First, input is "10", and then double.Parse(input) gives 10.

Check point 7: Create a program that finds and shows the sum of two numbers.
This means collect and convert input twice, and then show the sum.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 7 sample solution: 17

Question 28: Sometimes methods have to be applied several times. Is there a


way of simplifying this process to write less code?
Answer 28: Method nesting allows writing more compact code.

1. ReadLine() runs first. This means it returns a string from the user.
2. The string returned by ReadLine() is then passed into Parse(..).
3. Parse then returns a numerical value, which is stored to input.
1. ReadLine() is the nested method.
2. Parse(..) is the nesting method.
Line above is equivalent to the two below.

Check point 8: Write code to divide two doubles. Be sure to use method nesting
to both collect and convert input.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

18
Check point 8 sample solution:

Question 29: Is there some other way of repeatedly calling methods?


Answer 29: Method chaining is the process of calling several methods in sequence.
The following syntax applies: MethodOne().MethodTwo().MethodThree()
and so on.

1. ReadLine() runs first.


2. ToUpper() runs second.
3. Value is then assigned to s. same data types
1. 2.
3.
Check point 9: Write code that accepts a string, and then displays it all in lower
case. Use ToLower() to convert a string to lower case.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

19
Check point 9 sample solution:

Question 30: How can output be formatted so it looks more professional?


Answer 30: C# has format specifiers. These are codes that can be embedded in
strings to format output using currency, time and many other formats.

There are other format specifiers, but the logic is the same.

"C" formats as currency. "P2" formats as a percent.


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

20
Question 31: Sometimes it's not so easy to decide what data type might result
from a calculation. Is there a way to approach this?
Answer 31: The "var" keyword can be used. The compiler, which is responsible
for making executable programs, can recognize the actual data type based on
what's written on the right side.

Recognized as a string.
Hover your mouse over
var.

Recognized as a integer.

Recognized as a double.

Question 32: Strings are sequences of characters. Is there more to strings?


Answer 32: Strings are indexed, meaning each character can be addressed
with a number. Use Substring(index,1) to get a specific character in the string.
Y e s
index: 0 1 2

"Hello "+"World"="Hello World"


Hover your mouse over "+". This shows the defintion of this operator. Using "+"
with strings produces another string. This is called string concatenation.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

21
Question 33: How can the simplest decisions be made in C#?
Answer 33: C# has the "if/else" construct available for making decisions. As a
simple example, consider comparing two numbers. Follow the numbered arrows
to see the order of execution. "x>=y" is the logical condition to be checked.
1. Check condition, which is true, since 6>=5
2. Run the code
3. Exit

1. 6>=5 is true

2. Run code

3. Exit code

1. Check condition, which is false, since 4 is not 5 or more


2. Run the code
3. Exit

1. 4>=5 is false

2. Run code
3. Exit

Read as "greater than Read as "greater than" Read as "less than"


or equal to"

Read as "less than Read as "equal to" Read as "not equal to"
or equal to"
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

22
Question 34: How can if/else blocks be made to work with input and strings?
Answer 34: As an example, you can collect a string, and check whether it has
a certain letter. The Contains method can check for something like a character
inside a string.

Hover your mouse over Contains. It has a return type of bool. This is a true or
false value, so Contains can be used as a logical condition to work with if.
Check point 10: Write a program that performs each step below.
1) Accepts a string
2) Since users can type, for example, "hello", or "HELlo", write code
to convert the input to a consistent case, either upper or lower
3) For example, if string is "HEllo", Contains("e") returns false because "e"
and "E" are not considered the same. Your code has to fix this.

4) Check for the existence of a letter like d, or whatever you want


5) Print a message telling the user whether the letter has been found
6) Method chaining should be useful
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

23
Check Point 10 sample solution:

Question 35: Can if blocks without else blocks be written?


Answer 35: Yes, it's possible to have if blocks without else blocks. Follow the
numbered arrows to see what happens when the word "Dead" is entered.

1.

2.

3.

4.

5.

6.

In the code above, each if block is checked. These if blocks are independent, so
whether one runs or not has no impact on any of the other ones.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Question 36: Can if/else constructs be nested to produce very fine logic? 24
Answer 36: Yes. Nesting of constructs is always allowed, but the code can be
difficult to read. Follow the numbered arrows to see the execution order.

1.

2.

3.

4. exit

Question 37: How can a lot of output be produced quickly?


Answwer 37: C# has "while" loops. These are blocks of code that run repeatedly.
A counter variables keeps the loop going until the condition fails and the loop exits.

On the next page is a very careful analysis of the operation of this construct.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

25
The steps below outline how a while loop runs. Start at the top, and move down.
Because the counter begins at 1, and goes to 3, the loop runs three times. It then
exits in the fourth picture. Follow the numbers down the pictures carefully. Start
at 1, go to 2, 3, 4, and so on to 11, where the loop exits.
3. Return to top
1. counter=1
1<=3, so true

2. Run code to get output:

4. counter=2 6. Return to top


2<=3, so true

5. Run code to get output:

9. Return to top
7. counter=3
3<=3, so true

8. Run code to get output:

10. counter=4
4<=3, so false

11. Exit

If you close your eyes, and are able to run this loop in your imagination, you have
fully grasped it. Be sure to imagine it as a very structured sequence of steps. 4
steps are used to illustrate the essential character of this loop. Now imagine you
have to run 100,000 lines of code. Clearly, writing 100,000 lines of code by hand
would be a great waste of time and energy. Hence, the need for such things as
while loops.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

26
Question 38: I don't understand the while loop, or what it's doing. What
can be done to understand it better?
Answer 38: Use the "step into" feature of the debugger to go through the loop
with complete control, one step at a time. Press Debug->Step Into-> And
then press the little blue arrow that points down. Look for it carefully across
the top of the program.
Do these steps only once. Keep pressing this little arrow to keep looping.

1. 2. 3.
1.Start here

2.

3. counter is now 2

4.

5. counter is now 3

6.

7. counter is now 4,
so condition is false

8. exit
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

27
Question 39: How can if/else constructs be combined meaningfully with while
loops?
Answer 39: A common task might be to get a string, grab each character, and
then to examine that character to see whether it satisfies some condition. Type
and run this code with the debugger if you wish to truly understand.

If a matching letter is found,


the code runs as shown below. index++ is called
1. 5. every time
counter++ is called
2. only when a matching
letter is found
3.
4. If no matching letter is found,
the code runs as shown below.
General Steps: 1. 4.
1. Get string
2. Grab each character 2.
3. Examine character
4. Either add to counter or not
5. Advance index 3.
6. Go back to top
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

28
Question 40: Writing many if/else if../else blocks can be tedious and prone to
errors. Is there a better way?
Answer 40: The "switch" block can be used to examine a variable with multiple
possible values. You will benefit immeasurebly from running this code with your
debugger.

1.

2.
3.

4.

Follow the numbered arrows to see how such a block executes. Can you
reproduce the flow in your mind with your eyes closed? That is when you can say
you have truly understood.

Check point 11: Can you improve the program above so it can accept a string
input in varying cases, like "APPLE", or "AppLE", and still show the price?
1) Be sure you read the input from the command window
2) Be sure that the input is changed to a consistent case
3) Once you have your code built, run it with the debugger, step by step
4) Either on paper, or in your mind's eye, draw a numbered arrow diagram to
be sure you truly understand.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

29
Check point 11 sample solution:(Code changes in red boxes)

1.

2.

3.

4.

Question 41: What is a for loop, and what can be done with it?
Answer 41: For loops allow repeating blocks of code. They use an index variable.
Since strings are indexed, for loops can be used to step through the characters of
a string.

On the next page is a very careful analysis of the operation of this construct.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

30
Below is a very careful analysis of how a for loop actually runs.
The first time the loop runs, i=0. Follow the numbered arrows to complete the
first cycle.
1. Set i=0
1. 2. 4. 2. Check condition
3. Print
3. 4. Go to i++

When i=0, s.Substring(0,1) gets "H", which is at index 0 in the string

On all other cycles, the loop is reduced to the three steps below.
1. Check condition
1. 3. 2. Print
3. Go back to i++
2.

When i=1, s.Substring(1,1) gets "e", which is at index 1 in the string

On all other cycles, the loop is reduced to the three steps below.
1. 3. 1. Check condition
2. Print
2. 3. Go back to i++

When i=2, s.Substring(2,1) gets "y", which is at index 2 in the string

When the condition fails, the loop exits.


1.

2.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

31
Question 42: How can a for loop be run with the debugger?
Answer 42: The steps are outlined below.
Do these steps only once. Keep pressing this little arrow to keep looping.
1. 2. 3.

1. Set i to 1

2. Check condition

3. Run code

4. Increment i by 1

5. Check condition

6. Run code

7. Increment i by 1

8. Check condition. 3 is not  2,


so condition fails.

9. Exit
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

32
Question 43: Sometimes it's difficult to know when and why to introduce a
variable. Is there some reliable preliminary process that can be applied to help
decide when a variable is right?
Answer 43: Look for a numerical pattern. Then convert the numerical pattern
to symbolic form. Follow the arrows very carefully.
1. Look for a numerical pattern, like the changing values below.
2. Notice the starting value, and ending value.

i=0 i+1 i=1 i+1 i=2

Question 44: How can if's be combined meanginfully with for loops?
Answer 44: Think of a quantity that can be listed in some fashion, and then
think of some condition that can be applied to each item in the list

Notice that since only one line, WriteLine(...), runs after the if, no curly braces
are needed to enclose WriteLine(..). Remember that i is a variable, so as the loop
runs, it represents the values 1,2,3,4, and thus each of these can be checked to
decide whether it's even.

Check point 12: Can you produce an arrow diagram of the code in question 43?
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

33
Check point 12 sample solution:
Assume i is even, so it's Assume i is odd, so it's
divisible by 2. not divisible by 2
2. 6. 5. 2. 5. 4.
1. 1.

3. 3.

4.

Question 45: It seems like keeping track of an index variable can be challenging.
Is there some other mechanism for stepping through collections of various kinds?
Answer 45: The "for each" loop can be used to examine values in a collection of
items of a great variety of types. Wrting "(int)letter" changes the letter from
something familiar like "p" to its underlying numerical code. This is called
explicit casting. The string "s" is the collection of items to examine. Notice that
no index variable is required to step through the string.

The order of execution of this loop is outlined with numbered arrows below.
Follow them very carefully.
2. 1. 1., 3.

3. 2.

Assume this is the first cycle. These are the remaining cycles.
1. Grab s 1. Grab letter
2. Grab first letter 2. Convert to code and print
3. Convert to code and print 3. Grab next letter and so on...
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

34
Question 46: How can foreach loops be combined with if/else blocks?
Answer 46: Imagine a collection of items to examine. The foreach loops allows
grabbing each character, while the if/else block examine each character.

1. 2. 3. 5. 6.

7. 8. 9.

4.

The foreach loop grabs each letter, and the if/else construct prints it. The blank
' ' character is turned into a new line. Follow the output pictures on the right
from 1 to 9. Notice step 4. appears out of order, but it's not. It shows the cursor
moves down to the next line, proving a blank is turned into a new line. If you
run this code, you see the output below.

Check point 13: Notice that "Press any key..." is on the same line as "There".
Can you add one line of code to make "Press any key..." appear on its own line?
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 13 sample solution: 35


Solution is line of code in red box. It can't be inside the foreach,
for example, because then it would be printed many times.

Question 47: How can values be accumulated in a variable before the variable is
printed?
Answer 47: The symbol "+=" can be used to accumulate values,like numbers, or
even to build up a long string from short pieces.

As you can see above, the sum is first 11, and then grows to 18. The values are
are accumulated using the "+=". In the case of a string, this symbol might build
a long string from short strings.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

36
Question 48: To make a realistic application, it's necessary to be able to collect
input until a user wants to exit. How can this be done?
Answer 48: Use a while(true) loop to achieve this effect. The loop can be
controlled using the break and continue statements.

Steps: Input is collected 5, separate times.


1) Get input first
2) Enter loop
3) If string has "exit", break out
4) If no "exit" present, read again
5) Continue to top of loop Output
6) Repeat

When a break is hit, exit the When continue is hit, return to


while loop and print message. top of loop and begin again.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

37
Question 49: If/else constructs seem to occur frequently. Is there some more
efficient way of writing them?
Answer 49: C# has the ternary operator. This operator can be used to
streamline the writing of if/else blocks. The logic it expresses is the same.

Assume x=10, and y=4.


3. 1. 2.
Then the ternary operator
executes as shown.
1. Check condition 4.
2. Go to $"{x}>{y}"
3. Store $"{x}>{y}" to result
4. Print result

Assume x=4, and y=10.


Then the ternary operator 3. 1. 2.
executes as shown.
1. Check condition
2. Go to $"{y}>{x}" 4.
3. Store $"{y}>{x}" to result
4. Print result
The general form of this operator is "check condition ? run if true : run if false"
Check point 14: Write code to compare two values. Once they are compared,
print the smaller of the two values. This means change 1., 2. and 3. below in a
way that compares the values, stores the result, and then prints the result.
1. 2. 3.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

38
Check point 14 sample solution:
You should draw a flow diagram to be sure you truly understand.

Question 50: Sometimes two things must be true in order for something to
happen. For example, to qualify for a discount, a customer has to pay with cash,
and buy premium gas at a gas station. How can this be expressed in C#?
Answer 50: C# has the logical "and" operator. This operator returns a value of
true only when both sides of it evaluate to true.

Notice that both variables are of type boolean. Either gas is premium, or not.
Either cash is being used, or not. Each has only two possible values in this simple
example. On the next page is a very careful analysis of this operator.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

39
When both variables are true,
the code executes as shown.
1) Check usingCash 1. 2.
2) Check buyingPremiumGas
3) The "&&" returns true 3.
4) Print discount
5 )Exit

4.

When usingCash is false,


and buyingPremiumGas is
true, the code executes as shown.
1. Check usingCash 1.
2. buyingPremiumGas is not checked
3. Not checking Gas type is called
"short circuiting"
4. Print no discount message
5. Exit 2.

When usingCash is true, but


buyingPremiumGas is false, the
code runs as shown. 1. 2.
1. Check usingCash
2. Check buyingPremiumGas
3. Print no discount message
4. Exit

3.

4.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

40
Question 51: Is it possible to use the ternary and logical "and" operators together?
Answer 51: Combining the ternary and "and" operators produces streamlined code.
Imagine a person wants to ride a roller coaster. To qualify, this person must be
45 inches or more, and be with parents. We can express this as shown below.

1. Check "height" is greater than or equal to 45 inches


2. Check "withParents"
3.Get "You may ride."
4. Store "You may ride." to resut
5. Print result

4. 1. 2. 3.

5.

You can run this code with the debugger using the steps below.
Do these steps only once. Press this little arrow to step through the code.
1. 2. 3.
Hovering your mouse over "&&" shows a tip. This tip shows whether the operator
is currently returning true, or false.
Hover mouse over

Check point 15: Rewrite the code so that the height is accepted from the user.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 15 sample solution: (Code changes are in red box.) 41

Question 52: Objects in the world have features. For example, a console window
has features like its width. How can we access such features through C#?
Answer 52: C# has "properties". Properties in C# represent things like the height
or width of a window. Properties are like variables, but they can be coded to be
much smarter than variables. We will learn about coding properties later. For
now, let's use one that already exists.

WindowWidth property

Please be sure to count the x's and the last y above to confirm there are 20.
Hover your mouse of WindowWidth. This shows a tip. This tip contains much
useful information.
Property icon
Property data type
Location of property
Name of property
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Question 53: Strings are indexed. Imagine we want to extract a character at a 42


given position, but a user could enter -1 as an index. This is not allowed. How
can we write a small program that ensures that the entered index is within the
allowed range of indexes for a given string?
Answer 53: C# has the logical "or" operator, written as "||", that can be used to
ensure that the index entered by a user lies within the string. Of course, it can
also be used for many other things.
Length=3

no letter H e y no letter
index=-1 index=0 index=1 index=2 index=3
not allowed allowed allowed allowed not allowed
same as length

Or
no letter no letter H e y no letter no letter
index=-2 index=-1 index=0 index=1 index=2 index=3 index=4
not allowed not allowed allowed allowed not allowed not allowed not allowed
same as length greater than length
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

43
The code executes as shown when
leftSide and rightSide have the
values shown on the right. 1.
1. Check left side is true
2. Since left side is true, 2.
call WriteLine(..)
3. Exit
Not checking the right side is called
short-circuiting.

3.
The code executes as shown when
leftSide and rightSide have the
values shown on the right. 1. 2.
1. Check left side, which is false now
2. Since left side is false, check right side
which is true 3
3. Call WriteLine(..)
4. Exit

4. Exit

The code executes as shown when


leftSide and rightSide have the
values shown on the right. 1. 2.
1. Check left side, which is false
2. Check right side, which is false
3. Call WriteLine inside else block
4. Exit
3.

4.
Imagine leftSide is given the value "true". When leftSide is then compared against
"true" using "==", the result is another "true". 1. Compare
2. Gives back true
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

44
Check point 16: Can you rewrite the code to Question 53 so that it uses the
logical "and" operator? Below are some questions to guide you.
1) Draw a picture of a string, like "Hey"
2) The logical "and" must check that an index lies within the string
3) If the index is within the string, print the character at that index
4) If the index is not within the string, print an appropriate message

Length=3

no letter no letter H e y no letter no letter


index=-2 index=-1 index=0 index=1 index=2 index=3 index=4
not allowed not allowed allowed allowed not allowed not allowed not allowed
same as length greater than length

0<= index && index <s.Length

Question 54: Indexes occur in strings. But I can imagine storing a block of numbers.
How can that be done in C#?
Answer 54: C# has arrays. An array is a block of values. The values stored are
usually of the same data type, and each value can be set and read using an index.
index=0 -5 data type[ ] name of array = new data type[ size of array ]
index=1 3
index=2 10

Brackets indicate array

1. read value 1. read values


1. read value
2. stick into 2. add values
2. stick into
string 3. stick into string for printing
string
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 16 sample solution: 45

Question 55: Strings work well with for loops because strings are indexed. Since
arrays are indexed, can they work with for loops also?
Answer 55: The first entry in an array is at index 0. The last index is at the length
of the array, decreased by 1. Use these two ideas with for loops.
10 5 -6 8 Length is 4, but indexes go from 0 to 3, NOT 1 to 4.
index=0 index=1 index=2 index=3 General rule:Length=n, so indexes go from 0 to n-1

Array initializer
10 is at index 0, 5 at index 1, and so on

1. pretend i=0
1. pretend i=0
2. do array[0]*array[0]
2. then array[0]=10
3. print 100
3. print (10)^2
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

46
To make an array work with a for loop, be sure to iterate over the index values.
To set the value of i correctly, look at the picture. C# is smart enough to allow
writing double[] array={1,2,4,5.6}, without the "new double[]" on the right side.

i i i i
n n n n
d d d d
e e e e
x x x x

0 1 2 3

When this code runs, the following happens.


4 is the length of the array.
i=0, so 0<4 is true, and 10 prints
Allowed indexes i=1, so 1<4 is true, and 5 prints
i=2, so 2<4 is true, and -6 prints
i=3, so 3<4 is true, and 8 prints
i=4, so 4<4 is false, and the loop exits
Check point 17: Can you rewrite a for loop so that that i begins at 1? Below is a
picture of a for loop that begins with i=1. Running this code shows only 5,-6,
and 8. Can you fix it so it shows the 10 also?

Hint 1: It can be fixed with two small adjustments.


Hint 2: One adjustment has to be made to the header of the for loop.
Hint 3: One adjustment has to be made to array[i].
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 17 sample solution: 47

Just changing the condition does


not work because now i=4 at the end
and array[4] is not allowed.

Just changing what's inside


here does not work becaues
8 does not show.

Now at the end, i=4, but 4-1=3,


and the loop works.

In other words, writing "int i=1" has two consequences, and both must be handled
for the code to work properly.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Question 56: How can we collect several values at run time from a single line, and 48
then display some output after operating on each value?
Answer 56: We can read input with ReadLine(). This gives a string. We then have
to split the string by a separator like a comma, save the entries into an array of
strings, and then convert each entry to numerical form so it can be operated on.

On the left of the code are pictures of what's actually stored in memory. Notation
like [0] means the entry at index 0. When the array of doubles is first made, it
stores all zeros. This is true in general for doubles. To be more exact, the value is
0.0D.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

49
Question 57: There is a class of students. Each student has his or her grades. How
can this be expressed in C#?
Answer 57: We can convert a situation like this one into an array of arrays.
index=0 index=1
Corresponds to first student Corresponds to second student
index=0 index=1 index=0 index=1 index=2
test 1 test 2 test 1 test 2 test 3
89 98 76 89 91
Notation for nested, or jagged, arrays Grades for first student

Grades for second student

You can run this code with the debugger using the steps below. To truly know
what this code is doing at this point, please run it with the debugger now. It's
crucial as a step towards building real comprehension.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
There is more a more detailed discussion on the next page.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

2. Assign it 1. Make array of arrays 50

3. Grab new int[]{89,98} first using the outer foreach loop from studentGrades

4. Now print the grades, one by one,


using the inner for loop

5. Print the separator

6. Now grab new int[]{76,89,91} from studentGrades using the outer foreach loop.

7. Now print the grades, one by one,


using the inner for loop.

8. Print the separator

Question 58: Imagine an array that stores salaries for 3 people. How can the average
salary be found?
Answer 58: To find an average, apply the defintion of an average as the sum of the
values divided by the number of values.
sum of values add up all the values inside the array with foreach loop
average = =
number of values length of array

Check point 18: Rewrite the code so that it uses a for loop.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

51
Check point 18 sample solution: (Change to code in red boxes)

When i=0, salaries[0] gives 25000 and sum+=salaries[0] adds it to sum, so sum=25000.
When i=1, salaries[1] gives 34000 and sum+=salaries[1] adds it to sum, so sum=59000
When i=2, salaries[2] gives 45000 and sum+=salaries[2] adds it to sum, so sum=104,000

Check point 19: Can you extend the code so that the sum
is printed as it grows. Think of terms of
printing it at EACH execution of either a
for loop, or a foreach loop.
Question 59: It's easy to copy the number "5" from one place to another. How does
C# handle copying simple data types like doubles, decimals, and related types?
Answer 59: Simple data types like doubles are copied by value. This means that a
copy of the data is made, but no other relationship exists between the variables.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

52
Check point 19 sample solution: (Code changes in red boxes.)

Question 60: An array could store 1,000,000 values. Copying entries one by one
could take a long time. How does C# handle this?
Answer 60: Arrays are copied by reference. This means multiple names are made
that point to the same location in memory.

1. Set y={1,2} 3. 4. 6. 7. Set x={5,6} 9.


Set y={-4,-1}
2. 5. 8.
x=y means that x points to Automatically, x points to Automatically, y points to

In other words, In other words, In other words,


x[0]=y[0] and x[1]=y[1] x[0]=y[0] and x[1]=y[1] x[0]=y[0] and x[1]=y[1]

In other words, x and are two different names that reference the same memory.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

53
Question 61: How do I think more like a programmer?
Answer 61: Imagine you have a class of students. Each student has his or her own
grades. Find the average grade of each student.
1. Draw a picture, and label it clearly. Many times, the picture can be
a simplified version of the real situation.
Mary Louisa 2. Try an approach to the code based on simplicity and
Grades Grades directness. For example, turn Mary's grades into an
98 99
89 91
array, add the grades, divide by the total number of grades
85 86 and print as the average.

3. If you have many grades for each student, finding the sum by adding entries
together is not practical. Imagine, for example, adding 50 grades for one person.
Such a long addition is better done with a foreach loop. So add foreach loops.

Mary Louisa
Additional grades for each student shown as Grades Grades
98 99
ellipses 89 91
85 86
... ...
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

54
4. If there are many students, it's not practical to go through the process of
finding each average, for each student, manually. But we can think of a class
of students programatically as an "array of arrays".

....
Mary Louisa
Grades Grades ....
98 99
89 91
85 86 ....
Additional grades for each student shown as ... ...
ellipses
Additional students with their
grades are indicated by these
ellipses

Arrays are grabbed repeatedly. Loops are used repeatedly, so


This means an outer foreach can they have to be used in the
be used to represent this. final code also.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

55
Question 62: Placing too many lines of code inside Main() leads to code that can
be difficult to read. How can this be addressed?
Answer 62: C# allows creating methods. Methods are usually created to perform
a specific task, and allow breaking a huge amount of code into small, understanble
pieces.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.

This is the "calling code"

4. "double" is the
1. "static" means method 2. "void" means this method
data type of the
can be called directly does not send a value back 3. PrintIncreasedValue
is the name parameter
by typing its name. to the calling code
5. x is the parameter

2. To call a method means to write its name and,


1. in this case, pass in an argument. The argument
5. is a variable name like "input.

3. Argument goes into method


through parameter.

4.
x exists in this method
as a local variable.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 20: Create a program with a method. The purpose of the method is 56
to accept a decimal data type, and print it increased by 10%. Apply currency
formatting. You can make a few modificantions to the code in question 62.
Question 63: How can a method return a value to the calling code?
Answer 63: The return keyword can be used to send a value back to the calling
code.

This is the argument.

This is the method call.

Data type of variable


matches the data type
returned by the method

same data types


This is the value returned by the method.
It's a double dat a type. This is the same as the data type
keyword right after "static".

Send in x. This means send 45 along the numbered arrows 1.,2. , 3. The return
keyword sends back 49.5.

1.

2.

3.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

57
Check point 20 sample solution: (Code changes in red boxes)

x is of type decimal. 1.1 is double. The M is needed to ensure 1.1M is of type


decimal so that x*1.1M is the product of two compatible data types.
Question 64: Interest earned is defined as I=Pr, where P is the principle amount,
and r is the rate. I, in other words, needs two vaues to be found. How can we
create a method in C# to do this?
Answer 64: We can create a method that accepts two values. This means that it
has to have two parameters.

A more careful analysis follows on the next page.


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

58
After rate and principle are declared and set, they are passed into the body of
GetInterest as shown. Follow the arrows.

The names "rate" and "principle" are the variables. They are passed into the method
as the arguments. They go into the body of the method through the parameters.
variable variable

argument
argument

parameter

parameter

This is the string returned by GetInterest(..) so that


it can be printed with WriteLine(..).

Check point 21: Create a program with a method that accepts two values, and
returns the larger of the two.
1. Call the method Compare.
2. Make the parameters of type double.
3. Use the ternary operator to compare the values inside the body of method.
4. Return the larger of the two values.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 21 sample solution: 59


It's very important you run this, as all the code, with the debugger, step by step, if
you wish to build a true and complete understanding.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.

Question 65: Values of type double, integer, decimal and so on can be passed into
a method. Are the values passed as references to the same memory location, or as
copies of the data?
Answer 65: Simple types like the decimal type are passed by value. This means a
copy of the data is sent into the body of a method. The original variable is not
affected after the method call completes.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

60
Notice that it's okay to place method calls directly in strings.

If x=45, then writing AddTwo(x) sends a copy


of the value of x to AddTwo(double x)

Question 66: How can a method we've written be used with a program construct
like an if/else?
Answer 66: To create a method that works with program flow structures, the
method could return a "bool". We can check whether a number is even, or not.

Below are numbered arrow diagrams to show how this code runs. Please follow
the arrows very carefully.
3.
1.
3.
1.
4.

4.

2.
2.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

61
Question 67: Sending an array to a method could take a lon gtime if the array
were big. How are arrays passed to methods?
Answer 67: Arrays are reference type variable, so a reference to the array is passed
and no copy of the data is sent. This means changes to an array inside a method
are visible in the calling code.

Before ChangeArray
is called

1.
Changes made through arr are visible 3.
here through array.

2.
Inside the method, arr points to the same memory as
array.

array 1
2
arr
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

62
Question 68: How can a method operate on a variable number of values?
Answer 68: The params keyword can be used to create methods that operate
equally well whether 5 inputs or 25 inputs go on.

Two arguments being


passed into Add(..)

Four arguments being


passed into Add(..)

Six arguments being


passed into Add(..)

The number of arguments varies. The method "Add" is more flexible because of
this feature.
Check point 22: Can you create a program with a method that can multiply a
variable number of values? In other words:
1) Create a method called Mutiply
2) Make it return a double
3) Make it work so that it works whether you write Multiply(1,2) or
Multiply(1,2,4,5).
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

63
Check point 22 sample solution: (Important bits of code in red boxes)

1. Set product=1, not 0 at first. If you want the product of 2,4,5, you can't multiply
by 0 because the product would then always be zero.

To keep multiplying and storing back to the product, use "*=". This is the operator
used in this solution.

For example, with product=1 at first, we have the following:


product=1 means product stores 1
product*=2 means that product now stores 2
product*=4 means that product now stores 8
product*=10 means that product now stores 80

In other words, at each stage product stores the new, updated value.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

64
Question 69: How can a method set or return multiple values, and why is this
useful?
Answer 69: Methods can use the "out" keyword to and the return keyword. The
out keyword allows setting a value that then is accessible inside the calling code.
Before sorting

After sorting

Maximum value is at last index.


1. maxOut is declared, but it's not assigned a value.

2. When maxOut is passed into Summarize, put "out"


in front of it.

3. Use the "out" keyword as a modifier


on the parameter "max"

4. Calling Array.Sort(arr) sorts the array.


Now the highest value is at the highest
index. "arr.Length-1" is the highest index.
This line sets the value of max. Now it's
also available inside Main().

Check point 23: Extend the code in question 69 to also return the minimum value
of an array.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

65
Check point 23 sample solution:(Important bits of code in red boxes.)

Before sorting

After sorting

Question 70: What is a useful method that uses the "out" keyword already defined
in C#?
Answer 70: The double.TryParse(..) method is one that takes a string, and returns
a "bool", as well as a value that is the result of a successful conversion to numerical
form.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

66

TryParse(..) gives back a "bool", so it can be used with if(..).

xOut is produced if the conversion to numerical form


"input" is a string.
is successful.
Question 71: When we use the "out" keyword, the "out" value does not have to be
set. But imagine we set two values, and want to swap the values. How does C#
allow us to do this?
Answer 71: The "ref" modifer can be used to swap values. The effect is that the
changes made in called code is visible in the calling code.

This is the "calling" code.

This is the "called" code.

y=10
x=5
temp=x y=temp means
means y is now 5
temp=5
x=y means
x is now 10
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

67
Question 72: The world is made of many different kinds of objects. How can a
simple template for making objects be made in C#?
Answer 72: C# is objected oriented. In C#, a "class" is a template that allows
constructing objects. A particular object is called an "instance". Variables that
describe instances are called "instance variables".
height=65 height=60 height=55
name="Mary" name="Jenny" name="Suza"

per1 is an instance per2 is an instance per3 is an instance


of Person class of Person class of Person class
When you look at the pictures above, you see that the height and name change
from person to person. That is, height and name are both changing or variable
quantities. Please type and run this code with the debugger.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
Order Of Execution Follow the numbers
very carefully to understand how it actually
executes. Notation like 1,3 means this line is
hit twice.

2,5,8

1,3
4, 6
7,9

These are the instance variables.


This is the code that runs when
an object is actually constructed.

The "new" keyword indicates a new object


should actually be constructed.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

data type 68
"private" means name of instance variable
of variable
this variable is instance variables are also called "fields"
accessible only in
this class.

Sets value of name instance


variable for Mary.

data type
same as
class name

public Person(string n, double h) is a "parametrized" constructor. The parameters


are n, and h. You may imagine the parameter as a name through which the value
of "Mary" is passed into the body of the constructor so it can set the "name".
Below is the result of running the code using the debugger. At first, "mary" is
null, and after the code runs, mary has a height of 65, and a name of "Mary".
2.
Mary before:

1.

3.

4.

Mary after:

Little lock means "name"


5. is private
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

69
Check point 24:
Below are pictures of rectangles. Turn the pictures you see into C# code, just as
in the previous example.
1. Decide on the name of the class
2. Decide on the instance variables
3. Create a parametrized constructor
4. Inside Main, create instances of the class you've created

height=2 height=3 height=1


width=6 width=5
width=4
Question 73: It's now possible to create a class, and instantiate the class with a few
concrete objects. How can we display the instance variable values of an object?
Answer 73: Imagine our person class. People can speak. Speaking is an action, it's
something that can be done. Speaking is also a "behavior". In OOP, this means
we add a method to represent this behavior. OOP stands for "object oriented
programming".

Speak() method. This method


allows us to display the private
instance variable values.

method call
name of instance
The method "Speak" is public. This means this method can be called in code in
other classes. The instance variables are private, so they can be accessed only in
Person. Fields are usually private so that other code can't just change them.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

70
Check point 24 sample solution:

Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.

4. When you step through the program, you should see the Locals window. This
window shows you the variables, and their values.
name of class
also think of it
as the "type"
name of instance

name of instance variable


this is also called a "field"

name of instance variable value of height

code window

locals window
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

71
Question 74: What is member access, and how does IntelliSense work with
programmer defined classes?
Answer 74: Create a simple class. As you type, features of the class should become
visible in IntelliSense.

1. 2. 1. 2.

Available, programmer
defined members

dot represents "member access"


The general concept at this point is this: "name of object.name of member"
Either run the code above with the debugger
2
so you can be 100% clear on the way it executes,
or on the right is an approximate flow analysis. 5
Follow the numbers adjacent to the boxes
very carefully. Notation like 1., 3. means code begins
1, 3
there, goes to step 2. is, and then comes back to 3. 4,6

Check point 25: Convert the instructions below into a C# class.


1) Create a Canvas class to represent a canvas to be painted on
2) Add a string field to represent the "title" of the work
3) Add a method that can display the title of the work
4) Add a method that can draw a separator like "--------"
5) Create an instance of the of the Canvas class
6) Display the title of a canvas, and display the separator on the console screen
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

72
Check point 25 sample solution:

Either run the code above with the


2
debugger so you can be 100% clear on
the way it executes, or on the right is
an approximate flow analysis. Follow 5
the numbers adjacent to the boxes
very carefully. Notation like 1, 3 means
that line runs twice. 8

1, 3
4,6
7,9
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

73
Question 75: How can we create member methods that operate on input ?
Answer 75: Add parameters to the methods. Then pass values in to be processed
inside the methods.

Notice this code has no visible constructor. One, however, does exist, but the call
to it is not explicit here.
Either run the code above with the
debugger so you can be 100% clear on 3 Runs 20
the way it executes, or on the right is times
an approximate flow analysis. Follow
the numbers adjacent to the boxes 4

very carefully. Notation like 1., 3. means


that line runs twice. 1
2,5

Check point 26: Add a method to this class that can print a vertical line of a
specified length. The code you have to write is very similar to the code that
defines DrawSeparator(..).
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

74
Check point 26 sample solution: (Code addition in red boxes.)

Below is the order of execution of this code. Follow the numbers carefully.

3 Runs 10
times
4

7 Runs 10
times

1
2, 5
6, 8
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

75
Question 76: Does Visual Studio have a feature for summarizing the features of
a class?
Answer 75: Visual Studio 2015 has a class desinger, which can be accessed as
shown below. This feature provides a lot of summary information on a class.

Check point 27:


Explain the header of
the for loop.

Make sure the "Solution Explorer" is visible first.


1
2
Navigate to the Class Diagram
by following the numbers.

3 2
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

76
Check point 27 sample solution:

First time through loop

WindowWidth Second time through loop

Compare the header of the loop to the window right above it. The condition that
controls the execution of the loop is in the red box.
Question 77: Imagine we make a Canvas class, and give it a name. Then later we
decide we want to change and display the title. How can we do this?
Answer 77: Properties are features that objects possess. They are not behaviors.
For example, "Height" is a property. You don't do "Height". It's not an action.
Properties allow controlled access to backing fields.
This is a field. We have a property below.
So now you can think of this as the
"backing field"
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

public means property string is the data 77


can be reached in code outside type
this class name of property

Runs when property


is read
backing field
Runs when value
of backing field is set value sets backing field
value is present as a keyword
Sets property value
Reads property value
object name.Property Name

Either run the code in this question with


the debugger, or trace the execution by 2
following the numbers next to the boxes
very carefully. Notation like 10,12 means
this line is hit a couple time.
The class diagram now shows the 5,11
features below.

1,3
4,6
7,9
10,12

Check point 28: Create a class called "Person". Add a backing field called "name".
Add a property called "Name". Be sure you then read the name inside Main().
Do not code a "set" block.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 28 sample solution: 78

Question 78: If we have an "Age" property, a user could attempt to set its value
to something like -10. How can we prevent such errors?
Answer 78: We can add logic to properties to ensure that the backing field is
given only sensible values.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

79

This is the code that ensures that


the "value" set to age is within 0 to 120 years.

This is how the age field is read. Notice it's accessible all the way down in the call
to WriteLine(..) because it's all within the same class.
Check point 29: Modify the example in question 78 to answer each question:
1) What is the default value of age?
2) What's the value set to "age" when a user tries to set it to 454?
Question 79: How can a program with two classes be written?
Answer 79: We can add two classes to one file. We can expose the members of a
class by making them public.

Only the public Title property is reachable here.


M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 29 sample solution: (Code changes in red boxes.) 80

(Continuation of question 79)


Either run the code in question 79 with "title" field
the debugger, or below is an reachable
approximate flow analysis. Follow the only in code
numbers very carefully. inside blue
box

Public "Title" property


1,3
4,6
is reachable inside class
Program.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

81
Question 80: Can properties be coded in some other way?
Answer 80: C# has auto-implemented properties. Use these when the get and set
blocks do not require additional logic.

This is the automatically implemented


property. A title can be just about anything,
so no logic to check anything.

Automatically implemented
property is set directly inside the
constructor.

Price property requires logic to


be applied to set.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Question 81: Remembering the order of parameters when there are several could 82
be a little hard. Is there an easier way?
Answer 81: C# has named arguments. Named arguments allow sending values
in any order.

constructor parameter list

list of named arguments

name of argument value of argument

3rd position, counted from left

The named argument is in 2nd position, but it's still sent to the correct parameter.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

83
Question 82: How can we keep track of the number of instances of a class?
Answer 82: C# has static fields. These are fields that operate on the class level,
so they can be used to store information about the number of instances of a class.

Either run the code above with the


debugger so you can be 100% clear on
the way it executes, or on the right is
an approximate flow analysis. Follow
the numbers adjacent to the boxes 2,8

very carefully. Notation like 1, 3 means


that line runs twice.
5,11
static keyword

static property
1,3
4,6
7,9
name of class name of property 10,12
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

84

One copy of "counter" is


shared among all the
instances of Person.

Check point 30: What happens when an attempt is made to access a static field
through an object? Make a modification to the code in question 82 to find out.
Question 83: Since there are static fields and static properties, are there also
static methods, and even static classes?
Answer 83: C# has both static methods and static classes. One useful example of
this is the Math class.
Math class is stored in System.

Object of type "Math" cannot be created.

"Math" is much more conceptual than something like a "table". You can easily
imagine a table, but "Math" cannot be imagined so easily as a physical object. In
other words, "Math" does not need to have fields that have to be set. A table on
the other hand needs fields like color, number of legs and so on.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

85
Check point 30 sample solution:
"per1" is the name of a person object. Notice that IntelliSense does not show the
"Counter" property as an option to call on this object.

(continuation of question 83)


1 2

Round is stored inside Math, so we can write Round(y/x,2).


1. First, y/x runs
2. Then the result is rounded to two decimal places
Question 84: It could be difficult to add new entries to an array. Is there a better
way of storing many items of the same kind?
Answer 84: C# has generics. More on these will follow later, but one of the most
useful classes is the generic list class.

makes new list string is the data type

Add is a method that can store


values to a list. input
This operator reverses truth values.
It's the "logical negation" operator. output
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

86
The code in the previous question is a little more advanced. Please be sure to
type and run it with the debugger.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.

Question 85: How can a programmer defined data type be used as a parameter
in a method call?
Answer 85: We can imagine a book class. Books are stored in book shops.

It is crucial to building real comprehension that you type this code, and run it with
the debugger, step by step. As code grows, understanding can grow also, but only
if correct learning methods are embraced. Rushing does not work.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

87
Below is an approximate flow analysis of this code. Be sure to follow the
numbers next to the boxes very carefully. Notation like 1,3 means that line is
hit twice.

2,5

Makes new list of books.

Book type is used as parameter


9,12

15
runs
2 times

1,3
4,6
7
8,10
11,13
14,16

Question 85: Behind the scenes, computers love only numbers. People love names.
How can the two be reconciled?
Answer 85: C# has enumerations, which are lists of named constants. There are
prebuilt enumerations like ConsoleColor.

named constant

name constant
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

88
To make an enumeration, think of a list of numbers that can also be named
meaningfully. A common example is the days of the week.

Days.Monday prints as (int)Days.Monday prints as


Monday the number 1. The presence of (int) causes the
underlying value to be extracted.
Check point 31: Notice that Wednesday is not set to a number. Enlarge the
enumeration to include Thursday and Friday. Print their underlying numerical
values.
Question 86: Many objects share characteristics. How can common features be
stored in only one place so that less code can be written?
Answer 86: C# has inheritance. This mechanism allows common features to be
centralized in a parent class. Child classes inherit these features.
Imagine we have a limited universe of only three interface objects. Below we have
a text box, and a scroll box.
1. Notice that both of these can be resized. Because this feature applies to both, we
can create a base class called InterfaceObject, and place a field inside there called
resizable.
Text box is resizable

Scrollbar is resizable
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Check point 31 sample solution: (Code addition highlighted in boxes.) 89

(question 86 continued)
To turn the objects described earlier into code, create a base, or parent, class
called InterfaceObject, and then proceed as outlined below. It makes sense for
Scrollbar and TextBox to inherit from InterfaceObject because each "IS-A" kind
of interface object. For example, you see them both and you can interact with
both of them.

This code cannot run. There is no entry point in the form of "Main()". We
continue on the next page.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

90
Now Main() is present, so the program can be run.

base(resize) causes the base class


instructor to be called with the value
of "resize" passed up to the constructor
for InterfaceObject.

The locals window confirms that the box and bar objects have inherited the
resizable field.

If not for inheritance, there would be more code because we'd have to declare
the same field in multiple places. Now imagine a real application with dozens of
fields, methods and properties. Clearly, any ability to centralize code immediately
leads to less code. Next is a careful analysis of the execution of this code.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

91
On the right is an analysis
the order of execution of
this code. It's important to
observe that the code begins
3,8
inside Main(), and climbs all
the way up to the constructor for
InterfaceObject.

7,9

2,4

1,5
6,10

On the right is an analysis of how 5


"true" goes up through the code
to be set inside the constructor
for InterfaceObject. At the end of the
process, because "resizable" is inherited,
it's also an instance variable for "box".
2 3

1
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

92
Click the steps on the right to view the
class designer.
1

3 2

This field is inherited by


child classes.

Arrow indicates
inheritance

This class only uses


ScrollBar and TextBox,
so there is no arrow. A
"Program" is not an
"InterfaceObject", "TextBox"
or "ScrollBar".
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

93
Question 87: Fields are inherited. What happens to properties?
Answer 87: Properties are also inherited. Class diagram shows
how TextBox inherits
from InterfaceObject

Now the box object consists of a field, and a property. This property is public,
so it can be called inside Main.

Check point 32: Take the example from question 87 above, and add one class.
Make the class inherit from InterfaceObject. Be sure inside Main() you can
call the public property from the base class. Confirm inside the locals window
that this new object has both the private "resizable" field, and public property.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

94
Check point 32 sample solution: (Code additions in red boxes.)

The locals window confirms that now both box, and bar have inherited the
resizable field, and the Resizable property.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Question 88: We can centralize fields and properties. Can we extend this same 95
logic to methods?
Answer 88: C# has virtual methods. The purpose of these methods is to centralize
logic that is common to multiple classes. It is absolutely necessary to type this
code, and run it with the debugger. This will illustrate the order of execution with
complete precision.

The most important observation here is that the GetDesc() is virtual. This means
it stores code that will be used by child classes. If this were not so, this code would
have to be recreated in multiple classes. If you had several hundred products it
would be a huge waste of energy to type "Price:{price:C}" 500 times, when it can
be done once inside the base class. Imagine further that the base class stored 10
common fields, and they had to be formatted. Then clearly it's easier to type
base.GetDesc() then to write code for 10 different fields inside each of 500 classes.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

96
On the right is an
approximate flow
analysis starting from
the call to GetDesc().
Please follow the numbers
very carefully.

3
"virtual" keyword. Place
default code inside this
method. Default means it's
code that can be used by
many child classes equally
well.

2
4
"override" keyword means
this method refines or adds
unique code. Here, uniqe
means the addition of code
to display the page count.
1,5

1 2

This bit is unique to books, so it


base.GetDesc() calls GetDesc() adds refinement, or, if you like, it
in base class, so this is code reuse. makes GetDesc() more specific.

Check point 33: You're going to extend the code in question 88 above.
1) Add a country of origin field
2) Decide where to place this field
3) Add code to display the value of this field
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

97
Check point 33 sample solution: (Code changes in red boxes.)

The locals window shows the composition of the book object.

Inherited field
Specific to book class
Inherited field
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

Question 89: Is there some other way of writing less code?


98
Answer 89: C# has polymorphism. The word polymorphism means "having many forms". The specific form
an object assumes depends on context. It is crucial to real comprehension you type this code, and run it with the
debugger, step by step. This will immediatly give the commnets clear meaning.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

99

Each derives from Product class.

Makes list of products.


bk, and bg are treated as "products".
This is polymorphism.
Now each "prod" is treated either as
a book, or a bag. This is "polymorphism"
again.

When "prod" is a book, GetDesc() from the book class is called. This is called
"run time polymorphism". In other words, "prod" has now the form of a "book",
and therefore, the correct method from the Book class is called.

When "prod" is a bag, GetDesc() from the bag class is called. This is called
"run time polymorphism". In other words, "prod" has now the form of a "bag",
and therefore, the correct method from the Bag class is called.

1
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

100
When prod is a book, the code
executes as shown. Please follow
the numbers next to the boxes
very carefully.

3 5

bk is stored in products list.


It has the form of a product
at this point. This is the first
example of polymorphism.

2,6
now "prod" stands for a book,
so the correct, derived version
of GetDesc() is called. This is
the second example of polymorphism.

Check point 34: Can you draw an execution diagram to illustrate the order of
execution when prod becomes a "bag" inside the foreach loop?
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

101
Check point 34 sample solution:

When prod is a bag, the code


executes as shown. Please follow
the numbers next to the boxes
very carefully.

bg is stored in product list. 3 5


It has the form of a product
at this point. This is the first
example of polymorphism.

2,6

Now "prod" is a bag, so the


correct, derived version of GetDesc()
is called. This is "run time polymorphism".
Great Benefit: A single list stores objects of many kinds. Without, you'd have to
make many, different lists, adding code needlessly.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com

To navigate to the course on udemy.com, follow the link below. Normally,


this course sells for 100 bucks, but you get an 85% discount, so it's only 15
bucks to you.

https://www.udemy.com/beginnerscsharp2015/?couponCode=amz

Please visit the link below to see the full, 19 hour curriculum.
https://www.udemy.com/beginnerscsharp2015/?couponCode=amz

Вам также может понравиться