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

Post on 11-Jan-2016

215 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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 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.

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

44

Value Types Example

int i;

int j;

...

i = 42;

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

j now holds the value 42

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.

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.

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)

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.

99

Example

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

10

New Project

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.

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;

}

13

Circle.cs

public bool Is_Greater_Than(Circle other)

{

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

{

return true;

}

else

{

return false;

}

}

}

14

Main Program

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

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(); }}

1616

Comparison of Reference Types

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();

}

}

18

Comparison of Reference Types

End of Section

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.

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++

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.

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();

}}

2323

Passing an int to a Method

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

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; }

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:

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

2828

Passing a Circle to a Method

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.

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.

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(); }}

3232

Call by Reference Example

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.

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.

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.

36

Modify Reference Type Parameter

Restore the Circle code Modify it as shown on the following

slides.

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();

}

38

Modify Reference Type Parameter

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

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);

}

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();

}

41

Passing a Reference Variable by Reference

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

End of Section

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.

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(); }}

4444

“out” Parameter Example

End of Section

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.

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

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++

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.

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.

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.

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}

...}

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);

}

}

}

}

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

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.

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;

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;

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.

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.

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.

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?

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

}

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();

}

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.

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();

}

6565

Assignment

Read Chapter 8

End of Presentation

top related