Download presentation
Presentation is loading. Please wait.
1
C# A Quick Guide for HCI Yingcai Xiao
2
C# References http://www.learncs.org/
3
C# Basics Moving from C++/Java to C#
4
Data Structures + Algorithms
What you should do to design a language? How can you design a language? Computer: a device for data processing storing and processing data Programming = Data Structures + Algorithms Computer Languages: tools for users to define data structures to store the data and to develop algorithms to process the data. Data Types: System-defined Types & User-defined Types
5
Common Type System (CTS)
CTS defines Data Types for .NET Framework. C# is designed with CTS in mind. C# has the most efficient implementation of CTS.
6
Data Types in (CTS) Primitives (int, float, …)
System-defined Types (SDTs): Primitives (int, float, …) User-defined Types (UDTs): Classes Properties Structs Interfaces Enumerations Events Delegates Generics Templates
7
Common Type System (CTS)
Named Space: grouped code, used to resolve naming conflicts. namespace mine { int i=10; } namespace his int i=20; mine.i = his.i;
8
Named Space Example namespace WP1.CS.UA { class Hello public Hello()
System.Console.WriteLine("Hello, world."); } namespace WP2.CS System.Console.WriteLine("Hello, again!");
9
Named Space Example namespace WP { class Test
public static void Main() WP1.CS.UA.Hello mc = new WP1.CS.UA.Hello(); WP2.CS.Hello mc2 = new WP2.CS.Hello(); }
10
Classes Class: a group of code and data to be instantiated to form objects. Four categories of class members: Fields: member variables Methods: member functions Properties: fields exposed using accessor (get and set) methods Events: notifications a class is capable of firing
11
Example: How to define a class (user-defined data type)
class Rectangle { // Fields protected int width = 1; protected int height = 1; // Methods public Rectangle () { } public Rectangle (int cx, int cy) width = cx; height = cy; }
12
Example: How to define a class (user-defined data type)
// Accessor Methods public void setWidth(int w) { width = w; } public int getWidth() { return width; } public void setHeight(int h) { height = h; } public int getHeight() { return height; } public int area() { int a; a = height*width; return a; } // End of Rectangle class
13
Example: How to use a class (user-defined data type)
Rectangle rect = new Rectangle(2,4); rect.setHeight(8); rect.setWidth(rect.getWidth() * 2); double darea = (double) rect.area();
14
Differences between C++ & C#
Ending a block with a semicolon Class myClass{ … }; } Object instance creation myClass myObject; //myObject is an instance myClass *myPointer = new myClass(); //myPointer is a pointer to an instance myClass myReference //myReference is a reference (an internal pointer) to an instance Dereferencing myPointer-> myReference. Class members Fields: member variables Methods: member functions Properties: fields exposed using accessor (get and set) methods Events: notifications a class is capable of firing Freeing heap memory free(myPointer); Automatically by garbage collection when myReference is out of extent.
15
Internal Memory Structures of Data Store
16
What is Data Type? 8 Data types describe the memory layout of objects.
The name of an object is the name of the memory space stores its data value. For example, int i = 8; “i” is the name of the memory space for storing the data value 8. i 8
17
C++ Pointer 0x12345678 int width int height Rectangle ()
A pointer in C++ is a memory location that stores an address. Rectangle *rect = new Rectangle (3, 4); rect 0x int width int height Rectangle () Rectangle (int w, int h) Area () 3 4 0x Dereferencing rect-> int area = rect->Area(); Please note the notation difference between a “pointer/reference” and a “name” in this lecture.
18
C++ Function Pointer 0x01234567 a = height*width; return a;
A method is a (function) pointer that points to the code location of the method in the “text” memory, i.e., the pointer stores the address of the code location of the method in the “text” memory. Area 0x a = height*width; return a; 0x (text memory)
19
Instantiating a Class (in CTS & C#)
Class Name; In CTS: “Rectangle rect” declares a reference of class Rectangle. A reference to a Rectangle object. rect “rect” is the name of a memory space that stores a reference. This is similar to Java. A “reference” is an internal pointer, it needs to “point” to an object before being dereferenced.
20
References in C# 0x12345678 int width int height Rectangle ()
Rectangle rect = new Rectangle (3, 4); // Use the second constructor rect 0x int width int height Rectangle () Rectangle (int w, int h) Area () 3 4 0x Dereferencing int area = rect.Area();
21
The “Object” class The root class of all other classes.
So, an object of any class is an “Object” So we can write: Object obj = new Rectangle (3, 4); Constructor: Object () String output: ToString() Read matadata: GetType() Clean up: Finalize()
22
The Object Class: System.Object
System.Object : root class for all other classes. Every class inherits the Finalize( ) method from System.Object. It is called just before an object is destroyed by the garbage collector of CLR. The time of call is determined by CLR not by the program. Use System.GC.Collect() to force a garbage collection (system wide, time consuming). Destructor in C++ is called just before an object is destroyed by the program, when the object is freed (for heap objects) or out of scope (for stack objects).
23
C# Multithreading
24
Multithreading Multithreading is a mechanism for performing two or more tasks concurrently. In the managed world of the common language runtime, the fundamental unit of execution is the thread. A managed application begins its life as a single thread but can spawn additional threads. Threads running concurrently share the CPU (or CPUs) by using scheduling algorithms provided by the system. To an observer, it appears as if all the threads are running at once. In reality, they simply share processor time. .
25
Multithreading A single-threaded application uses just one processor at a time. A multithreaded application can have different threads running on different processors. Windows NT kernel (NT, 2000, XP, Vista, 7, 8) supports multiple processors using a strategy called symmetric multiprocessing (SMP). Versions that derive from Windows 95 (95, 98, Millennium) do not. .NET Framework’s threading API: to start, stop, manipulate, prioritize and synchronize threads.
26
Example using System; using System.Threading; class MyApp {
static void Main () for (int i=0; i<10; i++) { Thread thread = new Thread( new ThreadStart(ThreadFunc)); thread.Name = "My thread # " + i; thread.Start (); }
27
Example static void ThreadFunc () {
String name = Thread.CurrentThread.Name; for (int i=0; i<10; i++) { for( int j=0; j< ; j++); //work System.Console.WriteLine (name + " running at "+ DateTime.Now); }
28
Multithreading Starting a thread: Create a thread object.
Setup a function for the thread to run. Start the thread. Thread thread = new Thread (new ThreadStart (ThreadFunc)); thread.Start (); 4. Start simply makes the thread eligible to be allotted CPU time. The system decides when the thread begins running and how often it’s accorded processor time. 5. When a thread function returns, the corresponding thread ends. Alive and Suspend if (thread.IsAlive) { thread.Suspend (); }
29
Foreground Threads vs. Background Threads
An application doesn’t end until all of its foreground threads have ended. It can, however, end with background threads running. The IsBackground property defaults to false, which means that threads are foreground threads by default. Up to the application to determine a thread is foreground or background. Example, application ends as soon as it’s started because it changes the auxiliary threads from foreground threads to background threads:
30
Foreground Threads vs. Background Threads
using System; using System.Threading; class MyApp { static void Main () for (int i=0; i<10; i++) { Thread thread = new Thread (new ThreadStart (ThreadFunc)); thread.IsBackground = true; thread.Start (); } static void ThreadFunc () DateTime start = DateTime.Now; while ((DateTime.Now - start).Seconds < 5);
31
Threads Priorities Once a thread is started, the amount of processor time it’s allotted is determined by the thread scheduler. Thread.Priority can influence how much or how little CPU time a thread receives relative to other threads in the same process. Statistically not precise. Setting a thread to higher priority impacts not only other threads in the same application but also slows down other applications too. Thread Priorities ThreadPriority.Highest ThreadPriority.AboveNormal ThreadPriority.Normal (the default) ThreadPriority.BelowNormal ThreadPriority.Lowest thread.Priority = ThreadPriority.AboveNormal;
32
Multithreading in Action
Many applications intrinsically have two threads of execution: (1) Computation thread carries on the main computational task. It runs the computational loop. (2) User interface thread waits for user interaction. It may abort the computational thread if the user elect to do so. It runs the event loop.
33
Multithreading in Action
The Sieve and MultiSieve are examples of such applications: a computational component for searching prime numbers and a GUI for user interactions. The Sieve example is not multi threaded, the user can’t interact with the application whence the computation starts. CSExamples\Sieve The MultiSieve example is multi threaded, the user can cancel the computation after starting it and the application can exit in the middle of the computation. CSExamples\MultiSieve
34
Thread Synchronization
The hard part of designing a multithreaded program is figuring out where concurrently running threads might clash and using thread synchronization logic to prevent clashes (e.g., reading while writing to the same variable) from occurring. NET Framework provides the synchronization primitives to support applications’ synchronization logic. AutoResetEvent: Blocks a thread until another thread sets the event Interlocked: Enables simple operations such as incrementing and decrementing integers to be performed in a thread-safe manner ManualResetEvent: Blocks one or more threads until another thread sets the event Monitor: Prevents more than one thread at a time from accessing a resource Mutex: Prevents more than one thread at a time from accessing a resource and has the ability to span application and process boundaries ReaderWriterLock: Enables multiple threads to read a resource simultaneously but prevents overlapping reads and writes as well as overlapping writes
35
Thread Pooling Instead of launching threads yourself, you pass requests to a thread pool manager. The thread pool manager maintains a pool of threads that’s sized as needed to satisfy incoming requests. NET Framework provides the ThreadPool class as an API to the managed thread pooling. You must never terminate a pooled thread. The thread pool manager creates pooled threads, and it terminates them, too. You can use Thread’s IsThreadPoolThread property to determine whether a thread is a pooled thread.
36
Thread Pooling class MyApp { static int count = 0; static void Main ()
WaitCallback callback = new WaitCallback (ProcessRequest); // start the threads from the pool to run the callbacks ThreadPool.QueueUserWorkItem (callback); ThreadPool.QueueUserWorkItem (callback); ThreadPool.QueueUserWorkItem (callback); ThreadPool.QueueUserWorkItem (callback); Thread.Sleep (5000); // Give the requests a chance to execute }
37
Thread Pooling static void ProcessRequest (object state) {
int n = Interlocked.Increment (ref count); // lock then increment count Console.WriteLine (n); }
38
C# EDP Constructs Both day & Eve stop here at the end of week 4.
39
Event Mapping & Dispatching
Events A menu in C++: char c; bool done = false; while(!done) { cout << “Please make your selection, q to end:” cin >> c; switch(c) { case “+”: add( ); break; case “-”: sub( ); case “q”: done = true; } Event Loop Event Event Mapping & Dispatching Event Handler Monday, Day
40
Events & Delegates • C# has built-in constructs to support EDPs (event-driven programs). Event loop and event mapping for such applications can be very complicate. C# (.NET) has built-in event loop and event dispatching. C# provides constructs for programmers to define events and to register event handlers to events.
41
Events & Delegates • How can we register event handlers written by us to the event loop written by Microsoft? • The system event loop was implemented before the application event handlers and the names of the handlers are not pre-specified. • Event handlers are also called “callback methods”. Events are also called messages. • .NET implement this by using event & delegate constructs.
42
Events & Delegates • A delegate is a type-safe wrapper around a callback method. • Callback methods are used to respond to events. Three steps to understand events & delegates using an example Define a callback method to use a predefined Timer class Examine the Timer class which uses event & delegate Analyze the internal code of delegate
43
Usage of a Predefined Timer Class
// Call this callback method every 6 seconds. void UpdateData (Object sender, ElapsedEventArgs e) { // Update Data every 6 seconds. } // A Timer class has been implemented for us to use. // It has an event: Elapsed. Timer timer = new Timer (6000); timer.Elapsed += new ElapsedEventHandler (UpdateData); We registered a function pointer, UpdateData, as a callback, created a new instance of ElapsedEventHandler (a delegate) that wraps around (delegates to) UpdateData (a callback method) to respond to the Elapsed event.
44
Defining Events & Delegates
Inside the Timer class: public delegate void ElapsedEventHandler (Object sender, ElapsedEventArgs e); // specifies arguments for the callback public class Timer { public event ElapsedEventHandler Elapsed; … } // Calling the callback methods when the event occurs if (Elapsed != null) // Make sure somebody's listening, use Elapsed as a reference. Elapsed (this, new ElapsedEventArgs (...)); // Fire! Use Elapsed as a method, its arguments are sent to the callback methods.
45
Events & Delegates cont.
• A delegate is defined by placing the key word, delegate, in front of a global method. • The arguments of the method in the declaration are those of the callback functions. • The “real” argument of a delegate is always a pointer (to the callback function). • In the declaration of an event object, the type specifier between the “event” key word and the object name specifies the delegate to be used by the event to invoke event handlers. • An event object can be used as a reference and a method. • When an event object is used as a method, its arguments are sent to the callback methods, which are specified by the related delegate.
46
What’s Inside Events & Delegates?
public delegate void ElapsedEventHandler (Object sender, ElapsedEventArgs e); Compiles to: public class ElapsedEventHandler : MulticastDelegate // System.MulticastDelegate { public ElapsedEventHandler (object target, int method) { ... } public virtual void Invoke(object sender,ElapsedEventArgs e) { ... } ... } Use an event’s instance name as a method, actually call the Invoke method. It is a better way (a type safe way) to implement function pointers. (
47
More C# Features (similar to C++ or Java)
Both day & Eve stop here at the end of week 4.
48
Exception
49
Exception Handling What happens if a run-time error occurs before the PC reaches the return statement in a method? And you don’t have a computed value (say, the square root of the input, or the file handle of a disk file) to return yet. Where do you place PC after returning? How can you tell the caller don’t continue on the normal execution path since there is no returning value? How can you tell the caller what went wrong?
50
Exception Handling Exception Handling (object-oriented event-driven runtime error handling) The CLR defines how exceptions are thrown and how they’re handled. (How exception “events” are generated and how they’re handled by exception “event” handlers). An exception is thrown when a run-time error occurs. You can thrown an exception any where in the code. You can throw an exception in any language and catch it in any other. You can throw exceptions across machines
51
Exception Handling CLR’s Exception Handling Mechanism: try, catch, finally, and throw File file = null; // Do not define it in the try block. Why? try { file = new File ("Readme.txt"); if(file != null) { /* Do the work here. */} … } catch (FileNotFoundException e) { Console.WriteLine (e.Message); } catch ( … ) { … } finally { // Always come here even if there were exceptions. if (file != null) file.Close ();
52
Exception Handling • The CLR calls the handler that most closely matches the type of exception thrown. • All of the exception types defined in the FCL are derived directly or indirectly from System.Exception. • FCL exception classes contain a Message property, which holds an error message describing what went wrong, and a StackTrace property, which details the call chain leading up to the exception. • Exception handlers can be nested. • Code in a finally block is guaranteed to execute, whether an exception is thrown or not. • An exception that is best handled by the caller rather than the callee. • Programmers can throw exceptions defined in FCL or their own exceptions derived from System.ApplicationException. if (value > 0) width = value; else throw new ArgumentOutOfRangeException ( "Width can’t be negative."); Finished
53
Interface
54
Interfaces Interfaces
An interface is a group of zero or more abstract methods Abstract methods have no default implementation. Abstract methods are to be implemented in a child class or child struct. Subclassing an interface by a class or struct is called implementation of the interface. An interface can be implemented but not instantiated. You can’t use an interface class to create an object. Interfaces can also include properties and events, but no data. An interface defines a contract between a type and users of that type. Used to define software interface standards. All interface methods are public, no specifiers needed. A class can implement multiple interfaces.
55
Interface Example interface ISecret {
void Encrypt (byte[] inbuf, byte[] outbuf, Key key); void Unencrypt (byte[] inbuf, byte[] outbuf, Key key); } //no implementation, just prototyping. class Message : ISecret { public void Encrypt (byte[] inbuf, byte[] outbuf, Key key) { /* implementation here */ } public void Unencrypt(byte[] inbuf, byte[] outbuf, Key key) } Message msg = new Message(); // e.g. check if object msg implements interface ISecret if (msg is ISecret) { // type checking, // an object of a child type is also an object of the parent type, but not the other way around ISecret secret = (ISecret) msg; // from child to parent, explicit cast secret.Encrypt (...); Day 2/18/2016, vDx next, abstract, done with value type property, but not boxing
56
Abstract Class An abstract class is a class that can’t be instantiated, i.e., one can’t use an abstract class to create an object. The definition of an abstract class looks like a regular class except the preceding keyword “abstract”. It can have member fields and methods. It can only be used as a base class for subclassing. Its subclasses can inherit its methods as default implementation. (They can overwrite those methods too.) It is not allowed to inherit from multiple abstract classes.
57
Abstract Class vs. Interface Classes
Both can’t be instantiated. Both defines standards for their subclass to implement. An abstract class defines the minimal implementation of its subclasses. An interface has no implementation at all. A child class can’t subclass from more than one abstract classes. No multiple inheritance for abstract classes. A child class can implement more than one interfaces. Multiple inheritance allowed for interfaces. Abstract classes and interfaces can be used together.
58
Abstract Class & Interface Examples
abstract class DefaultTokenImpl { private readonly string name; public string ToString() { return name; } protected DefaultTokenImpl(string name) { this.name = name; } } interface IToken { string ToString(); } interface IVisitable { void Accept(ITokenVisitor visitor); } interface IVisitableToken : IVisitable, IToken { } class KeywordToken : DefaultTokenImpl, IVisitableToken { public KeywordToken(string name) : base(name) { } void IVisitable.Accept(ITokenVisitor visitor) { visitor.VisitKeyword(ToString());}
59
Abstract Class & Interface Examples
KeywordToken subclasses the abstract class DefaultTokenImpl It also implements the interface IVisitableToken (which implements interfaces IVisitable and IToken) It implements the Accept abstract method specified in interface IVisitable (a parent of IVisitableToken) It inherits the default implementation of ToString from the abstract class DefaultTokenImpl to implement the ToString abstract method specified in interface IToken (the other parent of IVisitableToken).
60
Generics
61
C# and CLR Generics Generics : parameterized types
According to Microsoft ( Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace. You can create your own generic interfaces, classes, methods, events and delegates. Generic classes may be constrained to enable access to methods on particular data types. Information on the types used in a generic data type may be obtained at run-time by means of reflection.
62
Enumeration
63
Enumerations Enumerations • a set of named constants
• similar to enum in C++ (not defined in Java until JDK 1.5) • implicitly derives from System.Enum enum Color { Red, Green, Blue } Color.Red // Red Color.Green // Green Color.Blue // Blue Color mycolor; mycolor = Color.Green; Console.WriteLine(mycolor); // Green
64
Enumerations Inside Enumerations Defining a set of named constants.
By default, it starts with 0; can be changed to any number. enum Color { Red = 10, Green, Blue } By default, it increments by 1 for each subsequent name. You can sign a value to each name. Red = 10, Green = 20, Blue = 21 You can increment a enum variable. Color mycolor; mycolor = Color.Green; mycolor += 1; Console.WriteLine(mycolor); // Blue
65
C# Features Beyond C++/Java
66
Property Can we make the member fields secure and easy to use at the same time? Eve starts here, 6/18/2016
67
Encapsulation and convenience
We protected member fields: width and height. (Encapsulation) (1) Securer code. Methods not belonging to the class hierarchy can’t access protected members. If we don’t want anyone change the value of “width”, we just don’t provide the setWidth() method. (2) Easier to maintain the code. We can rename “width” to “w” without impacting the users of the “Rectangle” class. (3) Tedious to implement and use. If we define the member fields as public, the usage would be much easier. rect.width *= 2;
68
Example: Accessor Methods for Protected Fields
class Rectangle { // Fields protected int width = 1; protected int height = 1; // Methods public Rectangle () { } public Rectangle (int cx, int cy) width = cx; height = cy; }
69
Example: How to define a class (user-defined data type)
// Accessor Methods public void setWidth(int w) { width = w; } public int getWidth() { return width; } public void setHeight(int h) { height = h; } public int getHeight() { return height; } } // End of Rectangle class
70
Example: How to use a class (user-defined data type)
Rectangle rect = new Rectangle(2,4); rect.setHeight(8); rect.setWidth(rect.getWidth() * 2); double darea = (double) (rect.getWidth() * rect.getHeight() );
71
A new construct in C# named “Property” makes member fields secure and
easy to access at the same time.
72
Example: How to define properties
// Properties defined as grouped accessor methods // in the Rectangle class public int Width // group name { get { return width; } set // the input parameter is implicit: value if (value > 0) width = value; else throw new ArgumentOutOfRangeException ( "Width must be 1 or higher"); }
73
Example: How to define properties
public int Height // a field defined by type and accessor code { get { return height; } set if (value > 0) height = value; else throw new ArgumentOutOfRangeException ( "Height must be 1 or higher"); }
74
Example: How to define properties
public int Area // a property of only get method { get { return width * height; } }
75
Properties are defined in the following format:
Defining Properties Properties are defined in the following format: protected type field-name; public type property-name { get { /* return the field value */ } set { /* reset the field value */ } } A property definition is composed of a protected or private field a property to expose the field which in turn consists of at least one accessor (get()/set()).
76
Using Properties Properties are used the same way as public fields. Rectangle rect = new Rectangle(2,4); rect.Width = 7; rect.Width *= 2; // Double the rectangle's width int area = rect.Area; // Get the rectangle's new area //Typecast a property “value” from int to double double darea = (double) rect.Area; Advantage of Properties: allow users to access private/protected fields as if they were public fields.
77
Notes on Properties Properties are public methods (set and get) used like fields. Data is secured (encapsulated) and access is simplified. (2) The set and get methods are called accessors. A property may not have the set (read-only properties) or the get (write-only properties), but can not miss both. (3) The implicit input argument, value, for the set method has the same type as the property. (4) The type of a property must be the same as the type of the field member it protects. (5) A property can’t be overloaded, e.g., we can’t define a “public double Area { … }” after defining “public int Area { … }”. You have to use a different property name, e.g. doubleArea, to define the area property of type double.
78
Why we have to name properties of different types differently?
Signature of a method: name, number of arguments, types of the arguments. Return type is not part of the signature. Overloading: two or more methods have the same name but different arguments. Name Mangling encodes the name of an overloaded method with its signature (by the compiler). The internal names of the methods are unique (no internal overloading). Property do not have any arguments, so the only way to differentiate properties of different type is by their names.
79
Internal Memory Structures of Reference & Value Types
Eve ended here, 2/18/2016
80
Instantiating a Class (in C++)
Class Name; In C++: “Rectangle rect” declares an object of class Rectangle. int width; int height; Rectangle () Rectangle (int w, int h) … rect “rect” is the name of a memory space that stores a Rectangle object.
81
Instantiating a Class (in CTS)
Class Name; In CTS: “Rectangle rect” declares a reference of class Rectangle. A reference to a Rectangle object. rect “rect” is the name of a memory space that stores a reference. This is similar to Java. A “reference” is an internal pointer, it needs to “point” to an object before being dereferenced.
82
References 0x12345678 3 4 Rectangle () Rectangle (int cx, int cy) Area
Rectangle rect; int area = rect.Area; // will not compile in C# Rectangle rect = new Rectangle (3, 4); // Use the second constructor rect 0x 3 4 Rectangle () Rectangle (int cx, int cy) Area int width Int height Rectangle () Rectangle (int w, int h) Area 0x Dereferencing is automatic for a reference. (No *rect or rect->) int area = rect.Area; Please note the notation difference between a “pointer/reference” and a “name” in this lecture.
83
Value Types int i; In CTS: is i a reference to an integer or just an integer? In CTS: i is an int (a system defined primitive type), not a reference to an integer. “i” is the name of a memory space that stores an integer value. int i = 8; i is a value type, for which we can directly store an integer value into the memory named as i. Compiler already allocated memory to store the value and we don’t need to “new” to allocate memory to store the value. i 8
84
Value Types Fields of value types have the object (not reference) memories allocated by the compiler and can be used as an object directly without “new”. Can we define user types behave like value types? Class is used to define user types, but need to be “new”ed before using. Memories are allocated at runtime. => Tedious and Slow.
85
Structs Structs: user-defined value types, less overhead and easier to use than classes. struct Point { public int x; public int y; public Point () {x = 0 ; y = 0; } public Point (int x, int y) { this.x = x; this.y = y; } } Point pnt1; // pnt1 is an object, not a reference. x = 0, y = 0 Point pnt2= new Point (); // pnt2 is an object, not a reference. x = 0, y = 0 Point pnt3 = new Point (3, 4); // pnt3 is an object, not a reference. x = 3, y = 4 // The compiler uses “new” to initialize an object. Point pnt4(3,4); is not allowed in CTS.
86
Summary: Value and Reference Types in CTS
In CTS, Value Types are Stack Objects: memory allocated at compile time on the stack auto destruction, no garbage collection needed less overhead, code runs faster less flexible, sizes need to be known at compile time In CTS, Reference Types are Heap Objects: memory allocated at run time on the heap garbage collected more flexible, sizes need not to be known at compile time more overhead, code runs slower Class defines reference types (heap objects) Struct defines value types (stack objects), even though “new” is used to create struct objects. Value types can’t derive from other types except interfaces.
87
Class Code class Point { public int x; public int y; }
Point p1 = new Point (); p1.x = 1; p1.y = 2; Point p2 = p1; // Copies the underlying pointer p2.x = 3; p2.y = 4; Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); Point p3; p3.x = 5; p3.y = 6;
88
Class Code class Point { public int x; public int y; }
Point p1 = new Point (); p1.x = 1; p1.y = 2; Point p2 = p1; // Copies the underlying pointer p2.x = 3; p2.y = 4; Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); // Writes "(3, 4)" Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); Point p3;//Creats a reference(pointer), no memory allocated p3.x = 5; // Will not compile p3.y = 6; // Will not compile
89
Struct Code struct Point { public int x; public int y; }
Point p1 = new Point(); //Creates a value object on stack. p1.x = 1; p1.y = 2; Point p2 = p1;//Makes a new copy of the object on the stack p2.x = 3; p2.y = 4; Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); // Writes "(1, 2)" Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); // Writes "(3, 4)" Point p3; //Creates a value object on the stack p3.x = 5; // It works. p3.y = 6; Console.WriteLine ("p3 = ({0}, {1})", p3.x, p3.y); // Writes "(5, 6)"
90
Arrays in C++ 5 10 0x 5 10 int a[2]; a[0] = 5; a[1] = 10;
// stack objects , size has to be known at compile time and can’t be changed at runtime. int size = 2; int *p; // a pointer p = new int[size]; p[0] = 5; p[1] = 10; // heap objects; dynamically allocated at runtime, “size” can be a variable delete p; // free the memory. a 5 10 p 0x 5 10
91
Arrays in CTS Array (same syntax for both class and struct):
Point[] pa = new Point[2]; pa[0] = new Point(); pa[1] = new Point(); Console.WriteLine ("pa[0] = ({0}, {1})", pa[0].x, pa[0].y); Console.WriteLine ("pa[1] = ({0}, {1})", pa[1].x, pa[1].y); Challenges: (1) Draw pictures to show the memory layout of pa for Point as a class and a struct. (2) What will happen when lines 2 and 3 are removed. Explain what will happen for Point as a class and then as a struct.
92
Boxing and Unboxing Boxing creates a copy of a value type on the managed heap (converts from value type to reference type) Unboxing duplicates a reference type on the stack (converts from reference type to value type) int val = 1; // Declare an instance of a value type object Object obj = val; // Box it, inexplicit cast, an object containing value “1” is created on the heap and pointed to by reference “obj”. int val3 = (int) obj; // This will work, explicit cast. int val2 = obj; // This won't compile. Why ?
93
Boxing & Unboxing Typecast: converting data from one type to another type. Widening: copying from a memory space of smaller value range to a memory space of larger value range. Narrowing: copying from a memory space of larger value range to a memory space of smaller value range. Boxing is widening and can be implicitly casted. Unboxing is narrowing and has to be explicitly casted. Monday Evening
94
Typecast References class Parent { int i; setParent(int k) {i=k;} }
class Child: Parent{ int j; public setChild(int m, int n) {i=m; j=n;} } Parent p1 = new Parent (); p1.setParent(1); Child c1 = new Child(); c1.setChild(2,3); // child objects can be treated as parent objects Parent p2 = (Parent) c1; p2.setParent(4); // don’t do this!!! parent objects can’t be treated as child objects Child c2 = (Child) p1; c2.setChild(5,6); Eve 2/23/16 will start here next.
95
Typecast References class Parent { int i; Parent(int k) {i=k;) }
You can typecast a child reference to parent reference, but never typecast a parent reference to a child reference. When we typecast the references, we do not alter the underlying objects (memory for the data.) Class type determines the memory layout. A child class inherits from its parent class, but not the other way around. A parent class does NOT inherit anything from its child classes. An object is an instance of a class, a real memory has the layout specified by the class. An object of a child type is an object of the parent type, but not the other way around. An object of a parent type is NOT an object of the child type. Day finished here. To Chapter 5. class Parent { int i; Parent(int k) {i=k;) } class Child: Parent{ int j; public set(int m, int n) {i=m; j=n;} Parent p1 = new Parent (1); Child c1 = new Child(); C1.set(2,3); Unboxing is narrowing and has to be explicitly casted.
96
NDD Nondeterministic Destruction (NDD) due to garbage collection.
No destructors in C# and Java (programmers don’t have to free memory). Finalize() method (inherited from Object class) is called during garbage collection. System decides when to perform garbage collection. File file = new File ("Readme.txt"); // file locked // Can’t delete “file” to release the file. file.Close (); // use close() to release the file in the Finalize().
97
NDD The Problem: we don’t know when file.Close() will not be called.
Solution One: Call Close() whenever you know the file is not needed, instead of in the Finalize(). Solution Two: Force a garbage collection by calling GC.Collect (). Very expansive. Finalize() for all not used objects in all applications will be called. Solution Three: Implement a Dispose method and call it when needed. (Read)
98
DLL Miss-matching The problem:
Many applications may share the same DLL, but may use different versions of the same DLL. A new application may not run correctly when linked into an older version of the DLL. The problem is solved in .NET. In .NET, one can use CLR’s Versioning, Strong Naming (SN), to avoid DLL miss-matching.
99
An Example Assembly: Math.dll
Simple.netmodule Complex.netmodule
100
Strong Naming Replacing GUID (Globally Unique Identifier)
Including the following data name of the assembly version of the assembly culture of the assembly (internationalization/localization) a public key a digital signature (= a hash of the assembly + the private key) Strong Naming info are added into the manifest of the assembly.
101
SN Assembly To Create a Strongly Named Assembly
(1) Create a key file for strong naming using the sn command in SDK. sn /k Keyfile.snk (2) Create the modules csc /target:module /out:Complex.netmodule Complex.cs vbc /target:module /out:Simple.netmodule Simple.vb (3) Use AL to create a strongly named assembly (version ) that uses the keys found in Keyfile.snk (version and key are written into the manifest). al /keyfile:Keyfile.snk /target:library /out:Math.dll /version: simple.netmodule complex.netmodule (typo in the book: space missing between /target:library and /out:Math.dll) (4) Create the application bound to the version Math.dll. csc /target:exe /reference:Math.dll Mathdemo.cs
102
SN Assembly Copy all needed files to the installation directory.
To install the application: Copy all needed files to the installation directory. MathDemo.exe, math.dll, Simple.netmodule, and Complex.netmodule run MathDemo.exe To verify that versioning is working, Create another version of Math.dll: al /keyfile:keyfile.snk /target:library /out:Math.dll /version: simple.netmodule complex.netmodule Copy the new Math.dll to the installation directory and run MathDemo.exe again. Will get System.IO.FileLoadException error.
103
Inside .NET Versioning (1) Versions are dynamically checked at runtime before loading DLLs. (2) Versions are strictly enforced. (3) To “update” a DLL you need use binding redirect. (5) Use “binding redirect” to link with different versions of DLLs and use “sn /T math.dll” to find the hash value of the dlls to be linked to. (all specified in MathDemo.exe.config)
104
Versioning in .NET // Versioning info can be specified in the config file for an application // MathDemo.exe.config <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Math" publicKeyToken="cd16a90001d313af" /> <bindingRedirect oldVersion=" " newVersion=" " /> </dependentAssembly> <probing privatePath="bin" /> </assemblyBinding> </runtime> </configuration>
105
GAC The Global Assembly Cache (GAC) is a repository for sharing (strong named) assemblies on an individual system. It is located at C:/Windows/Assembly. (1) Move math.dll and related files to any directory, say, Shared. (2) MathDemo will not run anymore. (3) Go to Shared: gacutil /i math.dll (4) MathDemo will run now. (5) To un-share (note: no dll extension): gacutil /u math
106
Coding with Strong Naming
Applying Strong Names Using Attributes in the Source Code (An easier way to produce a strongly named assembly). Add to Complex.cs Using System.Reflection [assembly:AssemblyKeyFile ("Keyfile.snk")] [assembly:AssemblyVersion (" ")] Add to Simple.vb Imports System.Reflection <Assembly:AssemblyKeyFile ("Keyfile.snk")> <Assembly:AssemblyVersion (" ")> The Version Number = major-version.minor-version.build.revision
107
Delayed Signing: to install and use a strongly named assembly
Delayed Signing: to install and use a strongly named assembly without the private key. (for development use only, not for release). al /keyfile:public.snk /delaysign /target:library /out:Math.dll /version: simple.netmodule complex.netmodule or [assembly:AssemblyKeyFile ("Public.snk")] [assembly:AssemblyVersion (" ")] [assembly:DelaySign (true)]
108
The Fundamentals of C# Basic CTS Types: Class, Struct, Property, Event, Delegate, Value Type, Reference Type, Enum Basic .NET Concepts: Garbage Collection, DLL, Versioning, Strong Name, GAC, Exception Handling, Try, Catch, Finally, Throw. What is it? How to define and use it? Can you write a program? Can you trace a program? Do you know what’s going on inside?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.