Questions
- What is the difference between
ref
andout
?
-
ref
variables are “read-only”, their value cannot change inside a method. -
ref
is a keyword,out
is not. - There isn’t any: they are both used to pass a reference to a method.
-
out
variables may not be initialized going into the method, but have to receive a value inside the method. - There isn’t any: they are both used to pass a value to a method.
Warm-up Exercises
-
Consider the following code:
-
What are the values of
x
,y
andz
- Before the
Foo
method is called? - Inside the
Foo
method? - After the
Foo
method executed?
- Before the
-
What is the value of
c
? -
What is the value of
d
?
-
Solution
Before the Foo
method is executed: 1, 2, and z
is not set.
Inside the Foo
method: 2, 1 and 3.
After the Foo
method: 1, 0, and 2
c
holds '*'
, d
holds %
.
Problems
-
Write the
AddRev
method (header included) such that the following:would display
Solution
-
Write the
AddLog
method (header included) such that the following:would display
Solution
-
Write the
AddReset
method (header included) such that the following:would display
Solution
-
Consider the “regular” implementation of the
Rectangle
class:And try to answer the following questions.
Solution
A possible solution to those questions is available.
-
Write a
Draw
method that takes one optionalchar
parameter and draw a rectangle of the calling object’s width and length using that character if provided,*
otherwise. If your method is correctly implemented, thenshould display
Solution
A possible solution is:
public void Draw(char symb = '*') { string drawing = ""; for (int i = 0; i < Length; i++) { for (int j = 0; j < Width; j++) { drawing += symb; } drawing += "\n"; } Console.WriteLine(drawing); }
-
Write a
Copy
method that does not take arguments, and return a copy of the calling object. If your method is correctly implemented, thenshould display
If the length of the original object changed after
copy.Length = 12;
was executed, then your method makes a shallow copy instead of a “deep” copy.Solution
A possible solution is:
public Rectangle Copy() { return new Rectangle(Width, Length); }
-
Write an
Equals
method that returntrue
if the calling object and the argument are both non-null rectangles with the same length and width,false
otherwise. If your method is correctly implemented, thenshould display
Solution
A possible solution is:
public bool Equals(Rectangle rP) { if (rP == null) return false; return rP.Length == Length && rP.Width == Width; }
-