11 values and references chapter 8. 22 objectives you will be able to: describe and compare value...

65
1 Values and References Chapter 8

Upload: shon-blankenship

Post on 11-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

11

Values and References

Chapter 8

Page 2: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

22

Objectives

You will be able to: Describe and compare value types and

reference types. Write programs that use variables of both

value type and reference type. Write functions that take value types and

reference types as parameters. Correctly use “ref” and “out” parameters

for methods. Write methods that modify variables in

the calling method. Use the generic “object” class correctly.

Page 3: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

33

Value Types

“Primitive” types like int are called value types.

A variable of type int holds the value of the variable.

An assignment to a different variable copies the value into that variable.

Just like C

Page 4: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

44

Value Types Example

int i;

int j;

...

i = 42;

j = i; // j gets the contents of i

j now holds the value 42

Page 5: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

55

Reference Types Variables of complex types are called

reference variables. Hold references rather than values.

Like references in Java and C++.

Similar to a pointer in C or C++ Except you can’t get its numerical value. You don't dereference it. You can only use it to get the object to

which it refers.

An assignment for a reference type copies the reference, not the object.

Page 6: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

66

Declaring Reference Types

Circle c1; // Space allocated for a

Circle c2; // reference only.

c1 = new Circle(5); // This creates a new object// Memory is allocated.

c2 = c1; // c2 and c1 now refer to the same object

The assignment statment does not create a new object.

No memory is allocated by the assignment statement.

Page 7: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

77

Comparison of Reference Types

Normallycomparison of reference type variables checks if they refer to the same object.

Different objects will always compare as unequal, even if the two objects are identical.

There are some exceptions, where a class overrides the comparison function. (String)

Page 8: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

8

Example – Comparing Reference Types

Let's look at some code to compare Circle objects for equality.

We will use an existing class definition. Write a Main() that will use the class.

Page 9: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

99

Example

Create a new Visual C# console application project. Delete “using’s” except System Delete “namespace ...”

Page 10: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

10

New Project

Page 11: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

1111

Example

Download Circle.cs to the project directory.

http://www.csee.usf.edu/~turnerr/Software_Systems_Development/Downloads/

Add Existing Item Circle.cs to the project.

Source code on the following slides.

Delete Namespace from Circle.cs. Delete Namespace from Program.cs.

Page 12: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

12

Circle.csusing System;

class Circle

{

private String name;

private double radius = 0.0;

public Circle(String n, double r)

{

name = n;

radius = r;

}

public String Name() { return name; }

public double Radius() { return radius; }

public double Area()

{

return Math.PI * radius * radius;

}

Page 13: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

13

Circle.cs

public bool Is_Greater_Than(Circle other)

{

if (this.Radius() > other.Radius())

{

return true;

}

else

{

return false;

}

}

}

Page 14: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

14

Main Program

Add code to main program as shown on the following slide.

Page 15: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

Comparison of Reference Types

using System;

class Program{ static void Main(string[] args) { Circle c1; Circle c2;

c1 = new Circle("Circle1", 5); c2 = c1;

if (c1 == c2) { Console.WriteLine("c1 and c2 are equal"); } else { Console.WriteLine("c1 and c2 are not equal"); } Console.ReadLine(); }}

Page 16: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

1616

Comparison of Reference Types

Page 17: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

Comparison of Reference Typesusing System;

class Program

{

static void Main(string[] args)

{

Circle c1;

Circle c2;

c1 = new Circle("Circle1", 5);

c2 = new Circle("Circle1", 5);

if (c1 == c2)

{

Console.WriteLine("C1 and c2 are equal");

}

else

{

Console.WriteLine("c1 and c2 are not equal");

}

Console.ReadLine();

}

}

Page 18: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

18

Comparison of Reference Types

End of Section

Page 19: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

1919

Variables Passed to Methods

When you pass a value type variable to a method, the method gets a copy of the value.

The method can modify the copy but this does not affect the original

value used by the caller.

Just like C.

Page 20: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2020

Variables Passed to Methods

When you pass a reference type variable to a method, the method gets a copy of the reference. The parameter in the method is an alias for

the object passed by the caller.

This means that the method can modify the original object passed (by reference) by the caller.

Like passing a pointer to a function in C. Or a reference in C++

Page 21: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2121

Variables Passed to Methods

Both calls look the same!

You have to know whether the variable being passed is a value type or a reference type.

Page 22: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2222

Example: Passing an int to a Method

class Program{ static void Set_Int (int target, int value) { Console.WriteLine ("Setting target to {0}", value); target = value; }

static void Main(string[] args){

int myInt = 10; Console.WriteLine ("The value of myInt is {0}", myInt); Console.WriteLine ("Calling Set_Int to set myInt to 100"); Set_Int (myInt, 100); Console.WriteLine ("Back from Set_Int"); Console.WriteLine ("The value of myInt is {0}", myInt); Console.ReadLine();

}}

Page 23: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2323

Passing an int to a Method

Page 24: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2424

Save this code for later use.

Use Ctrl-a to select all of Program.cs Use Ctrl-k Ctrl-c to comment out all

of the code. We will use it again later.

Modify Class Circle as shown on the following slide.

Type in new version of Program.cs

Page 25: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2525

Passing a Circle to a Method

public class Circle{ private String name; private double radius;

// Constructor public Circle(String Name, double Radius)

{ name = Name; radius = Radius;

}

public String Name () {return name; } public double Radius() {return radius;} public double Area() {return 3.141592 * radius * radius;}

public void Set_Radius (double new_radius) { radius = new_radius; }

Page 26: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2626

Passing a Circle to a Method

class Program

{

static void Set_Circle_Radius (Circle target,

double value)

{

Console.WriteLine ("Setting radius of {0} to {1}",

target.Name(), value);

target.Set_Radius(value);

}

static void Main(string[] args)

{

...

Replace set_int with this:

Page 27: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2727

Passing a Circle to a Method

static void Main(string[] args){ Circle myCircle = new Circle ("Circle A", 10);

Console.WriteLine ("The radius of {0} is {1}", myCircle.Name(), myCircle.Radius());

Console.Write ("Calling Set_Circle_Radius to set radius of " );

Console.WriteLine ("{0} to 100", myCircle.Name());

Set_Circle_Radius(myCircle, 100);

Console.WriteLine ("Back from Set_Circle_Radius");

Console.WriteLine ("The radius of {0} is {1}", myCircle.Name(), myCircle.Radius());

Console.ReadLine();}

http://www.cse.usf.edu/~turnerr/Software_Systems_Development/Downloads/Set_Circle_Radius.cs

Page 28: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2828

Passing a Circle to a Method

Page 29: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

2929

Call by Reference

You can write a method to take a reference to a value type as an argument.

Same as using a reference as a parameter in C++. Similar to using a pointer as a parameter in C.

Rather than passing the value to the method, the call passes a reference to the value. Caller must prefix argument with “ref”.

This permits the method to modify the caller’s variable.

Page 30: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

3030

Restore set_int example

Comment out most recent version of Program.cs.

Uncomment the original version Ctrl-k Ctrl-u

Modify original code as shown on the following slide.

Page 31: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

3131

Call by Reference Example

class Program{ static void Set_Int ( ref int target, int value) { Console.WriteLine ("Setting target to {0}", value); target = value; }

static void Main(string[] args) { int myInt = 10; Console.WriteLine ("The value of myInt is {0}", myInt); Console.WriteLine ("Calling Set_Int to set myInt to 100");

Set_Int ( ref myInt, 100);

Console.WriteLine ("Back from Set_Int"); Console.WriteLine ("The value of myInt is {0}", myInt); Console.ReadLine(); }}

Page 32: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

3232

Call by Reference Example

Page 33: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

3333

Variables Passed by Reference

The definite assignment rule still applies.

You can’t pass an uninitialized variable to a method, even with call by reference.

Page 34: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

34

Passing a Reference Variable by Reference

You can also specify ref on a parameter that is a reference type.

This does make a difference. The parameter is now an alias for the

variable passed by the caller. Without ref in the declaration, the

function gets a copy of the caller's reference.

Page 35: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

35

Passing a Reference Variable by Reference

Without ref in the parameter declaration the caller gets a copy of the caller’s reference.

If the function sets the parameter to point to a different object, the caller’s variable is not affected.

With ref in the parameter declaration the function can change the caller’s variable.

Page 36: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

36

Modify Reference Type Parameter

Restore the Circle code Modify it as shown on the following

slides.

Page 37: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

37

Modify Reference Type Parameter

static void Set_Circle_Radius(Circle target,

double value)

{

Console.WriteLine("Setting target to refer to new Circle");

Console.WriteLine("of radius {0} ", value);

target = new Circle("Circle B", value);

}

static void Main(string[] args)

{

Circle myCircle = new Circle("Circle A", 10);

Console.WriteLine("The radius of {0} is {1}",

myCircle.Name(), myCircle.Radius());

Console.Write("Calling Set_Circle_Radius to set radius of ");

Console.WriteLine("{0} to 100", myCircle.Name());

Set_Circle_Radius(myCircle, 100);

Console.WriteLine("Back from Set_Circle_Radius");

Console.WriteLine("The radius of {0} is {1}",

myCircle.Name(), myCircle.Radius());

Console.ReadLine();

}

Page 38: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

38

Modify Reference Type Parameter

In Main(), myCircle still refers to the same Circle object and it is unchanged.

Page 39: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

39

Passing a Reference Variable by Reference

Now modify the function to specify call by reference. Also modify the call.

static void Set_Circle_Radius(ref Circle target,

double value)

{

Console.WriteLine("Setting target to refer to new Circle");

Console.WriteLine("of radius {0} ", value);

target = new Circle("Circle B", value);

}

Page 40: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

40

Passing a Reference Variable by Reference

static void Main(string[] args)

{

Circle myCircle = new Circle("Circle A", 10);

Console.WriteLine("The radius of {0} is {1}",

myCircle.Name(), myCircle.Radius());

Console.Write("Calling Set_Circle_Radius to set radius of ");

Console.WriteLine("{0} to 100", myCircle.Name());

Set_Circle_Radius(ref myCircle, 100);

Console.WriteLine("Back from Set_Circle_Radius");

Console.WriteLine("The radius of {0} is {1}",

myCircle.Name(), myCircle.Radius());

Console.ReadLine();

}

Page 41: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

41

Passing a Reference Variable by Reference

In Main, myCircle now refers to a different Circle object.

End of Section

Page 42: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

4242

“out” Parameters

An “out” parameter for a method is like a “ref” parameter, except: The method can only write to it, not

read. The method must write to it.

Caller must prefix argument with “out”

The definite assignment rule does not apply to “out” parameters.

Page 43: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

4343

“out” Parameter Example

class Class1{ static void Set_Int (out int target, int value) { Console.WriteLine ("Setting target to {0}", value); target = value; }

static void Main(string[] args) { int myInt = 10; Console.WriteLine ("The value of myInt is {0}", myInt); Console.WriteLine ("Calling Set_Int to set myInt to 100"); Set_Int (out myInt, 100); Console.WriteLine ("Back from Set_Int"); Console.WriteLine ("The value of myInt is {0}", myInt); Console.ReadLine(); }}

Page 44: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

4444

“out” Parameter Example

End of Section

Page 45: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

45

Null Values and Nullable Types

Reference types can have the value null. Means "not set". Throws an exception if used for member. null is a keyword.

Can be used in assignments and comparisons.

There is no way to show that a normal value type is not set. The value 0 is not the same as null. You cannot assign null to a value type.

Page 46: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

46

Nullable Types

Value types can be made nullable by putting ? after the type.

Example:int? i = null;

Needed only in unusual situations

See pages 150 – 152 for details.

End of Section

Page 47: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

4747

The Stack and the Heap

Every program includes two memory areas set up and maintained by the runtime system: The Stack The Heap

Like C and C++

Page 48: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

4848

The Stack and the Heap

The stack is used for parameters and local variables of methods.

As in C.

As successive calls are made, the parameters and local variables for each call in turn are added to the stack.

Also the return address

Thus the “call stack”.

When a method does a return, or throws an exception, its local variables and parameters are “popped off the stack” and lost forever.

Page 49: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

4949

The Stack and the Heap

Memory for objects created with “new” is allocated from the heap. Like malloc in C and new in C++.

When the method that created an object finishes, the space is not automatically deallocated. The object can potentially still be accessed.

Unlike C and C++ you don’t need to free memory allocated on the heap. It will be freed automatically by the Garbage

Collector sometime after all references to it go away.

Page 50: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5050

The Stack and the Heap

The heap is not infinite.

Garbage collection will only deallocate memory used by objects that have no references.

If you create enough objects that have references, you will eventually get an OutOfMemoryException.

Page 51: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5151

Filling the Heap

class Circle{

private string name; private double radius = 0;

private Circle My_Model;

...

// A “Copy” constructor.public Circle (Circle Model){

radius = Model.Radius(); // Copy the model’s data name = Model.Name();

My_Model = Model; // Keep a reference to the model}

...}

Page 52: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5252

Filling the Heapclass Program

{

static void Main(string[] args)

{

Circle c1, c2;

int count = 0;

c1 = new Circle("Circle A", 5);

while (true)

{

c2 = new Circle(c1);

c1 = c2;

count++;

if (count % 1000000 == 0)

{

Console.WriteLine("count = " + count);

}

}

}

}

Page 53: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5353

OutOfMemoryException

On my desktop machine, this creates more than 70,000,000 Circle objects before bombing out with an OutOfMemory exception.

Takes several minutes!

Catch doesn’t work on OutOfMemoryException.

End of Section

Page 54: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5454

System.Object

In C# all classes are derived from class System.Object.

We will look at derived classes later. Similar to derived classes in C++.

For now, just be aware that an object of any class is also a member of class System.Object.

C# provides the alias “object”. Meaning is identical to “System.Object” Note capitalization.

Page 55: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5555

System.Object

If you declare a variable of class object, you can set it to refer to any object.

Circle c1;c1 = new Circle("Circle_42", 42);

object o;o = c1;

Page 56: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5656

Typecasting

If a variable of type object is really a Circle you can assign it to another variable of type Circle

but you have to typecast it.

Circle c1;c1 = new Circle(42);

object o;o = c1;

Circle c2;c2 = (Circle) o;

Page 57: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5757

Typecasting

object o;o = c1;Circle c2;c2 = (Circle) o;

If you didn’t include (Circle) this would get a compile error.

If you include (Circle) but o is actually not a Circle object, it will compile but will throw an exception at run time.

Page 58: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5858

Boxing

We sometimes need to store an integer as an object.

int i = 42; object o = i;

o is a reference. Must refer to a location on the heap. Variable i is a value on the stack. Logically this should be an error.

Page 59: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

5959

Boxing

The statement object o = i;

allocates space on the heap to hold an integer and copies the value of i into that space.

This is called boxing.A subtle source of performance issues in C#.

o refers to a copy of i.Changing either one has no effect on the other.

Page 60: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

6060

Unboxing

int j = o; // Doesn’t work

We have to typecast o.

int j = (int) o; // This does work.

What if o does not refer to an integer?

Page 61: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

61

Safe Typecasting

We can check whether a typecast is valid without risk of throwing an exception.

The is operator.

if (my_variable is sometype)

{

// Cast my_variable as sometype

}

Page 62: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

62

The is Operator

static void Main(string[] args)

{

int i = 42;

object o = i;

if (o is int)

{

int j = (int)o;

Console.WriteLine("j is " + j);

}

else

{

Console.WriteLine("j is not an int");

}

Console.ReadLine();

}

Page 63: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

63

The as Operator

Similar to typecast, but yields null if cast is not valid rather than throwing an exception.

Applies only to reference types and nullable types.

Page 64: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

64

The as Operator

static void Main(string[] args)

{

int i = 42;

object o = i;

int? j = o as int?;

if (j == null)

{

Console.WriteLine("j = null");

}

else

{

Console.WriteLine("j = " + j);

}

Console.ReadLine();

}

Page 65: 11 Values and References Chapter 8. 22 Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables

6565

Assignment

Read Chapter 8

End of Presentation