970 likes | 1.15k Views
Methods: A Deeper Look. 7.2 Packaging Code in C#. Framework Classes and libraries:. http://msdn.microsoft.com/en-us/library/ms229335.aspx. Old rule – methods fits on one page, not a bad idea, though not always doable. divide-and-conquer
E N D
7.2 Packaging Code in C# Framework Classes and libraries: http://msdn.microsoft.com/en-us/library/ms229335.aspx
Old rule – methods fits on one page, not a bad idea, though not always doable
divide-and-conquer Software 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
Variables characterized by attributes/properties • To design a type, must consider • Scope • Lifetime • Type checking • Initialization • Type compatibility
7.3 static Methods, static Variables and Class Math • Variables for which each object of a class does nothave 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.
Static more • 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 even more The static modifier cannotbe 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.
Variable Scope (refresher) classMyClass { intmyInteger; stringmyMessage; publicstaticintmyStaticInt = 100; publicintmyFunction() { returnmyInteger; } publicMyClass() { myInteger = 50; myMessage = "This is a string"; } } classProgram { staticvoid Main(string[] args) { MyClassmyC = newMyClass(); Console.WriteLine("Calling myFunction: {0}", myC.myFunction()); Console.WriteLine("Using a static member: {0}", MyClass.myStaticInt); Console.ReadLine(); } }
Why Is Method Main Declared static? Command-line • publicstaticvoidMain(stringargs[]) • During application startup, when no objects of the class have been created, the Main method must be called to begin program execution. The Mainmethod 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
is and Cast * voidMethod(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. strings = o asstring; // 2 // Causes a NullReferenceException of o is null. Assigns whatever //o.ToString() returns to s, no matter what type o is. strings = 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.
(Reminder) Two's complementFrom Wikipedia The two's complementof 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
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.
Floats science finance
Ex: float and decimal using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceDoubleVsDecimal { classProgram { staticvoid 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
const, readonlyand static readonly(const)* • 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 constkeyword and must be initialized as they are declared publicclassMyClass { public constdouble PI = 3.14159; }
const, readonlyand static readonly(const)* • 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 protectedinternal. • 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, readonlyand static readonly(readonly) • A read only member is like a constin that it represents an unchanging value. • The difference is that a readonlymember can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. publicclassMyClasspublicclassMyClass { { publicreadonlydouble PI = 3.14159; public readonlydoublePI; } publicMyClass() { PI = 3.14159 } } • Can have different values depending on the constructor used.
const, readonlyand static readonly(static readonly) • A readonlyfield can also be used for runtime constant: publicstaticreadonlyuint l1 = (uint)DateTime.Now.Ticks; • readonlymembers are not implicitly static, and therefore the statickeyword 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
const, readonlyand static readonly(static readonly) • In the staticreadonlycase, 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) • staticreadonlyis 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.
What is the difference betweenconstand static readonly? classProgram { publicstaticreadonlyTesttest = newTest(); publicstaticvoid Main(string[] args) { test.Name= "Program"; test = newTest(); // Error: A static readonly field cannot be // assigned to (except in a static constructor or // a variable initializer) } } classTest { publicstring Name; } On the other hand, if Test were a value type, then assignment to test.Name would be an error.
Objects again Host Program /Main
VerbatimString literals A 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";
7.5 Notes on Declaring and Using Methods 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
Assembling Strings with String Concatenation For values of simple types used in string concatenation, the values are converted to strings. If a boolis 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.
7.5 Notes on Declaring and Using Methods 1. Using a method name by itself to call a method of the same class—such as Maximum(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 staticmethod 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.
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.
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.
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)
Aliasing in C# C# has no pointers but references to an object. Rectanglebox1 = new Rectangle (0, 0, 100, 200); Rectangle box2 = box1; box1 and box2 refer to the same object. This object has 2 names:box1and box2. When two variables are aliased, any changes that affect one variable also affect the other. Ex.: box1.grow (50, 50);