1. 2 Framework Classes and libraries: 3

Preview:

Citation preview

Methods: A Deeper Look

1

2

7.2 Packaging Code in C#

http://msdn.microsoft.com/en-us/library/ms229335.aspx

Framework Classes and libraries:

3

4

Old rule – methods fits on one page, not a bad idea, though not always doable

divide-and-conquerSoftware reusability—existing methods can be used as building blocks to create new applications

• how to read data values from the keyboard—the Framework Class Library provides these capabilities in class Console

5

Variables characterized by attributes/properties

◦To design a type, must consider Scope Lifetime Type checking Initialization Type compatibility

6

7.3 static Methods, static Variables and Class Math

• Variables for which each object of a class does not have a separate instance of the variable. That’s the case with static variables.

• When objects of a class containing static variables are created, all the objects of that class share one copy of the class’s static variables.

• Together the static variables and instance variables represent the fields of a class.

7

Static member is not tied to a specific object It can be accessed without creating an instance of the

class Only one copy of static fields and events exists static methods and properties can only access static

fields and static events The static modifier can be used with

Classes Fields Methods Properties Operators Events Constructors

Static more

8

The static modifier cannot be used with indexers, destructors, or types other than classes

static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called.

Static (even more)

9

Variable Scope (refresher) class MyClass {

int myInteger;

string myMessage;

public static int myStaticInt = 100;

public int myFunction()

{

return myInteger;

}

public MyClass()

{

myInteger = 50;

myMessage = "This is a string";

}

}

class Program

{

static void Main(string[] args)

{

MyClass myC = new MyClass();

Console.WriteLine("Calling myFunction: {0}", myC.myFunction());

Console.WriteLine("Using a static member: {0}", MyClass.myStaticInt);

Console.ReadLine();

}

} 10

Why Is Method Main Declared static?

public static void Main(string args[])

During application startup, when no objects of the class have been created, the Main method must be called to begin program execution. The Main method is sometimes called the application’s entry point.

Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class.

Any class can have Main (sometimes used for testing)

◦ Project > [ProjectName] Properties... select the class containing the Main method that should be the entry point from the Startup object list box

Command-line

11

7.3 static Methods, static Variables and Class Math

12

C# almost everything is an object

13

is operator

14

is and Cast *

15

void Method(object o)

{

//Throws InvalidCastException if o is not a string. Otherwise, //assigns o to s, even if o is null (preferable)

string s = (string)o; //1

//Assigns null to s if o is not a string or if o is null. For this //reason, you cannot use it with value types (the operator could //never return null in that case). Otherwise, assigns o to s.

string s = o as string; // 2

// Causes a NullReferenceException of o is null. Assigns whatever //o.ToString() returns to s, no matter what type o is.

string s = o.ToString(); // 3

}

integers

Unsigned numbers can hold a positive value, and no negative value.There are different ways of representing signed integers. The simplest is to use the leftmost bit as a flag, but more common is twos complement .Signed integers can hold both positive and negative numbers.

16

(Reminder) Two's complementFrom Wikipedia

The two's complement of a binary number is defined as the value obtained by subtracting the number from a large power of two (specifically, from 2N for an N-bit two's complement). The two's complement of the number then behaves like the negative of the original number in most arithmetic, and it can coexist with positive numbers in a natural way.

8-bit two's-complement integers

17

Two's complement Examples

Ex: number 28 in 8 bit quantities

Step 1. 28 in binary form.

00011100

Step 2. Inversion. 0 ->1, 1 -> 0.

11100011

Step 3. Add 1

1110010

Ex: binary 11111111 00001001 to decimal

Step 1. This is a negative number (1 is first)

Step 2. Complement

00000000 11110110

Step 3. Add 1

00000000 11110111 = 247

Step 4. Decimal is -247.

18

Huge Integers

19

Floats

finance

science

20

Ex: float and decimal

using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace DoubleVsDecimal{ class Program { static void Main(string[] args) { double a = 0.2f; double b = 1.0f;

Console.WriteLine("{0}", a - b);

decimal c = 0.2m; decimal d = 1.0m;

Console.WriteLine("{0}", c - d);

Console.ReadLine(); } }}output: -0.799999997019768-0.8 21

Variable Scope (Visibility)

22

class Aclass{

public static const int BufferSize = 1024;}

23

the value of a const field is set to a compile time constant and cannot be changed at runtime

Constants are declared as a field, using the const keyword and must be initialized as they are declared

public class MyClass{

public const double PI = 3.14159;}

const, readonly and static readonly(const)*

24

PI cannot be changed in the application anywhere else in the code as this will cause a compiler error

Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.

Constants can be marked as public, private, protected, internal, or protected internal.

Constants are accessed as if they were static fields, although they cannot use the static keyword.

To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

const, readonly and static readonly(const)*

25

const, readonly and static readonly(readonly)

A read only member is like a const in that it represents an unchanging value.

The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.

public class MyClass public class MyClass

{ {

public readonly double PI = 3.14159; public readonly double PI;

} public MyClass()

{

PI = 3.14159

}

}

Can have different values depending on the constructor used.

26

const, readonly and static readonly(static readonly)

A readonly field can also be used for runtime constant:

public static readonly uint l1 = (uint)DateTime.Now.Ticks;

readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required. A readonly member can hold a complex object by using the new keyword at initialization.

static readonly field is set at run time, and can thus be modified by the containing class

27

const, readonly and static readonly(static readonly)

In the static readonly case, the containing class is allowed to modify it only in the variable declaration (through a variable initializer) in the static constructor (instance constructors, if it's not static)

static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.

Instance readonly fields are also allowed. 

Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field.  It specifically does not make immutable the object pointed to by the reference.

28

   

class Program {  public static readonly Test test = new Test();    public static void Main(string[] args) {    test.Name = "Program";       test = new Test();  // Error:  A static readonly field cannot be // assigned to (except in a static constructor or // a variable initializer)     }} class Test { public string Name; }

 On the other hand, if Test were a value type, then assignment to test.Name would be an error.

What is the difference between const and static readonly?

29

Objects again

Host Program /Main

30

Inheritance Idea

31

Reason for Classes/Objects

32

Class Access Modifiers Again

33

7.4 Declaring Methods with Multiple Parameters

34

Another way: return Math.Max( x, Math.Max( y, z ) );

35

36

37

Verbatim String literalsA verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple line

string a = "hello, world"; // hello, world

string b = @"hello, world"; // hello, world

string c = "hello \t world"; // hello world

string d = @"hello \t world"; // hello \t world

string e = "Joe said \"Hello\" to me"; // Joe said "Hello" to me

string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me

string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt

string h = @"\\server\share\file.txt"; // \\server\share\file.txt

string i = "one\r\ntwo\r\nthree";

string j = @"one

two

three";

38

39

7.5 Notes on Declaring and Using Methods

40

Your are not in c+

+ anymore

Assembling Strings with String Concatenation

This is known as string concatenation + (or the compound assignment operator +=).

When both operands of operator + are string objects, operator + creates a new string object in which a copy of the characters of the right operand is placed at the end of a copy of the characters in the left operand. For example, the expression

"hello " + "there" creates the string "hello there" without disturbing the original strings.

Every value of a simple type in C# has a string representation. When one of the + operator’s operands is a string, the other is implicitly

converted to a string, then the two are concatenated

41

Assembling Strings with String Concatenation

For values of simple types used in string concatenation, the values are converted to strings.

If a bool is concatenated with a string, the bool is converted to the string "True" or "False" (each is capitalized). All objects have a ToString method that returns a string representation of the object.

When an object is concatenated with a string, the object’s ToString method is implicitly called to obtain the string representation of the object. If the object is null, an empty string is written.

42

7.5 Notes on Declaring and Using Methods

1. Using a method name by itself to call a method of the same class—such asMaximum(number1, number2, number3) in line 18 of Fig. 7.3.

2. Using a variable that contains a reference to an object, followed by the member access (.) operator and the method name to call a non-static method of the referenced object—such as the method call in line 13 of Fig. 6.10, myGradeBook.DisplayMessage(), which calls a method of class GradeBook from the Main method of GradeBookTest.

3. Using the class name and the member access (.) operator to call a static method of a class—such as Convert.ToDouble(Console.ReadLine()) in lines 13–15 of Fig. 7.3 or Math.Sqrt(900.0) in Section 7.3.

43

7.6 Method-Call Stack and Activation Records

Stack: last-in, first out (LIFO) data structures—the last item pushed (inserted) on the stack is the first item popped off (removed from) the stack.

When an application calls a method, the called method must know how to return to its caller, so the return address of the calling method is pushed onto the program-execution stack (sometimes referred to as the method-call stack). If a series of method calls occurs, the successive return addresses are pushed onto the stack in last-in, first-out order so that each method can return to its caller.

The program-execution stack also contains the memory for the local variables used in each invocation of a method during an application’s execution.

This data, stored as a portion of the program-execution stack, is known as the activation record or stack frame of the method call. When a method call is made, the activation record for it is pushed onto the program-execution stack.

44

7.6 Method-Call Stack and Activation Records

When the method returns to its caller, the activation record for this method call is popped off the stack, and those local variables are no longer known to the application. If a local variable holding a reference to an object is the only variable in the application with a reference to that object, when the activation record containing that local variable is popped off the stack, the object can no longer be accessed by the application and will eventually be deleted from memory during “garbage collection.”

Of course, the amount of memory in a computer is finite, so only a certain amount of memory can be used to store activation records on the program-execution stack.

If more method calls occur than can have their activation records stored on the program-execution stack, an error known as a stack overflow occurs.

45

Variables Attributes Name - not all variables have them

Address - the memory address with which it is associated ◦ A variable may have different addresses at different times during

execution

◦ A variable may have different addresses at different places in a program◦ If two variable names can be used to access the same memory location,

they are called aliases Aliases are created via pointers, reference variables, C and C++ unions Aliases are harmful to readability (program readers must remember all of them)

46

Value types vs Reference Types

47

Aliasing in C#

C# has no pointers but references to an object.

    Rectangle box1 = new Rectangle (0, 0, 100, 200);   Rectangle box2 = box1; 

box1 and box2 refer to the same object. This object has 2 names: box1 and box2.

When two variables are aliased, any changes that affect one variable also affect the other.

Ex.:

    box1.grow (50, 50); 

48

Memory layout

49

Type Conversion (Casting)

50

Conversion Ex:namespace Conversion

{

class Program

{

static void Main(string[] args)

{

int i = 10;

short x = 5;

float f = 20.0f;

//i = x;

//x = i;

// f = i;

// i = f;

}

}

}51

7.7 Argument Promotion and Casting

52

53

7.8 The .NET Framework Class Libraryhttp://msdn.microsoft.com/en-us/library/gg145045.aspx

54

55

56

7.9 Case Study: Random-Number Generation (Next(Int32, Int32)Returns a random number within a specified range.)

57

58

59

60

61

62

7.10 Case Study: A Game of Chance (Introducing Enumerations)

63

64

65

66

67

68

69

7.11 Scope of Declarations

1. The scope of a parameter declaration is the body of the method in which the declaration appears.

2. The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block containing the declaration.

3. The scope of a local-variable declaration that appears in the initialization section of a for statement’s header is the body of the for statement and the other expressions in the header.

4. The scope of a method, property or field of a class is the entire body of the class.

• This enables non-static methods and properties of a class to use any of the class’s fields, methods and properties, regardless of the order in which they’re declared.

• Similarly, static methods and properties can use any of the static members of the class.

70

7.11 Scope of Declarations

71

72

73

74

75

Method Overloading (idea)

76

7.12 Method Overloading

77

78

79

80

7.13 Optional and Named Parameters

81

Variable Parameter List

82

83

7.14 Named Parameters

Normally, when calling a method that has optional parameters, the argument values — in order — are assigned to the parameters from left to right in the parameter list.

Consider a Time class that stores the time of day in 24-hour clock format as int values representing the hour (0–23), minute (0–59) and second (0–59).

Such a class might provide a SetTime method with optional parameters like public void SetTime( int hour = 0, int minute = 0, int second = 0 )

All of three of SetTime’s parameters are optional.

Assuming that we have a Time object named t, we can call SetTime

as followst.SetTime(); // sets the time to 12:00:00 AM

t.SetTime( 12 ); // sets the time to 12:00:00 PM

t.SetTime( 12, 30 ); // sets the time to 12:30:00 PM

t.SetTime( 12, 30, 22 ); // sets the time to 12:30:22 PM 84

7.15 Recursion

85

86

Nice Video on factorial

https://www.youtube.com/watch?v=ELjaRNQ4qWQ

87

88

7.16 Passing Arguments: Pass-by-Value vs. Pass-by-Reference

89

Pass-By-Value

90

Forcing Passing by Reference (ref)

91

Output Parameters (out)

92

93

94

95

ref similar to out, except ref  requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword

96

class Error

{

// compiler error "cannot define overloaded

// methods that differ only on ref and out"

public void SampleMethod(out int i) { }

public void SampleMethod(ref int i) { }

}

class OK

{

public void SampleMethod(int i) { }

public void SampleMethod(out int i) { }

}

97

Recommended