1 / 134

Welcome to CS215 Introduction to .NET / C#

Welcome to CS215 Introduction to .NET / C#. Kamen Yotov kyotov@cs.cornell.edu Department of Computer Science Cornell University. About the course. .NET / C# interesting features CLR CTS C# … Prerequisites CS211 (OO programming). Administrative. 1 Credit

ericam
Download Presentation

Welcome to CS215 Introduction to .NET / C#

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Welcome to CS215Introduction to .NET / C# Kamen Yotov kyotov@cs.cornell.edu Department of Computer Science Cornell University

  2. About the course • .NET / C# interesting features • CLR • CTS • C# • … • Prerequisites • CS211 (OO programming)

  3. Administrative • 1 Credit • Website: http://www.cs.cornell.edu/Courses/cs215 • Newsgroup: cornell.class.cs215 • When: MWF, 12:20-13:10, 09/02/02 - 09/27/02 • Add/Drop Deadline: 09/09/02 • Instructor: Kamen Yotov • Consultants/Graders: • TBA • Office Hours: • TBA

  4. Assignments & Grading • 4 assignments • Only programming (write-up inside) • Graded Pass/Fail • Demonstrations • Workarounds • Extra projects • More & interesting stuff…

  5. Resources • Visual Studio.NET Academic • May be I’ll use Academic features… • Distributions will be available • Books (optional) • Introduction to C# Using .NETRobert J. ObergPrentice Hall, ISBN: 0-13-041801-3 • Other • C# Language Specificationhttp://msdn.microsoft.com/vstudio/techinfo/articles/upgrade/Csharpdownload.asp • Websites… • Rotor • Search for it in Google!

  6. Topic 0:Introduction to .NET 09/02/02

  7. Topic 0: Introduction to .NETChallenges • Development: Which OS / Language? • Delivery: Media, Licenses, … • Stability: DLLs mess, Security • Maintenance: Who? What? • Services: The new model

  8. Topic 0: Introduction to .NETWhat is .NET • The combination of: • Framework • Common language runtime (CLR) • Class libraries • ADO.NET, ASP.NET, ... • Web Services • .NET Enterprise Servers

  9. Topic 0: Introduction to .NETWhat is .NET (cont.) Web Services Building Blocks (e.g. for Services) Office.Net ... ... .NET Applications Enterprise Servers Languages: C#, Visual Basic, etc SQL Server BizTalk ... Runtime Common Type System Common Language Runtime Services: .NET and COM+ .NET Framework Operating System

  10. Data & XML Base Classes Web Services UserInterface Common Language Runtime Base Frame Topic 0: Introduction to .NETWhat is .NET (cont.)

  11. Topic 0: Introduction to .NETWhat is the CLR? • Common type system • Mapping of data types. Programming language  Framework • Just-in-time (JIT) compilers • JIT compiles intermediary language (MSIL) into native code • Highly optimized for platform or device • Garbage collector • Permission and policy-based security • Exceptions • Threading • Diagnostics and profiling

  12. Base Class Library Support Thread Support COM Marshaler Type Checker Exception Manager Security Engine Debug Engine MSIL to Native Compilers (JIT) Code Manager Garbage Collector (GC) Class Loader Topic 0: Introduction to .NETWhat is the CLR?

  13. Topic 0: Introduction to .NETMore .NET • Namespaces and Classes • Hierarchical, unified class libraries • Unified and extensible provide “system” and base functionality and services • Object-oriented: everything is an object! • The systems uses the same classes offered to you • Interfaces • The .NET (Service) contracts • Types • Byte, Sbyte, Single, Double, String, Int16, etc. • These all map to the common type system

  14. Topic 0: Introduction to .NETWhat do you want to know? • Tell me what you want to know about .NET • I’ll try to incorporate it in the specific topic later • Discuss in the newsgroup

  15. Topic 1:Memory Management 09/04/02

  16. Topic 1: Memory ManagementDoing it manually • Allocate memory for a resource • Initialize the resource • Use the resource • Clean up the state of the resource • Free the allocated memory

  17. Topic 1: Memory ManagementGarbage Collection (Why?) • C/C++ applications often leak memory • Manual memory management • No clear rules for ownership of objects • COM fixes this partly through ref-counts • AddRef/Release calls must be balanced • SmartPointers don't catch all problems • Server applications must be leak free • Must run for months and years • Solution: automatic memory management

  18. Topic 1: Memory ManagementGarbage Collection (Why not?) • Garbage Collection downside: • Destructors called at some random future time • Finalization code is never synchronous • Breaks some established design patterns from C++ • Beware: Code should never depend on destructors to free external resources. • Instead: Implement IDisposable with using using (File f = new File("c:\\xyz.xml")){ ...} • IDisposable.Dispose() called on object when scope is exited.

  19. Topic 1: Memory ManagementGarbage Collection (How?) • Developer creates new objects and data arrays • Everything created/allocated using new keyword • The .NET runtime tracks all memory usage automatically • GC automatically removes all unused objects • More efficient memory management • Ease of use and "zero memory leaks"

  20. Topic 1: Memory ManagementGarbage Collection (What?) • Garbage collection • Generations • Resurrection • Disposability (Unmanaged Resources) • Finalization • Weak References • Assignment 1: • Study the GarbageCollection demo:<FrameworkSDK>\Samples\Technologies\GarbageCollection • Extra Credit: • Discover the objects reachable from a given object

  21. Topic 1: Memory ManagementGarbage Collection (Details) • GC Heap • Allocated Address Space • Allocation • Comparison C# vs. C/C++

  22. Topic 1: Memory ManagementGarbage Collection • Trace the roots all the way down • Mark all objects that are still alive • Remove all dead objects (sweep) • Compact the heap to remove holes

  23. Topic 1: Memory ManagementGarbage Collection (Finalization) • Similar to C++ destructors: public class BaseObj { public BaseObj() { } protected override void Finalize() { // Perform resource cleanup code here... // Example: Close file/Close network connection Console.WriteLine("In Finalize."); base.Finalize(); } } • Drawbacks in comparison to C++ • Slower to allocate finalizable objects • Slower to collect dead finalizable objects • Promotion • Actual method call • Ordering and time of finalization uncontrollable • Finalize not always called

  24. Topic 1: Memory ManagementGarbage Collection (Finalization) • Finalization Queue • Freachable Queue • Resurrection • Forced clean-up • GC.ReRegisterForFinalize(o) • GC.SupressFinalize(o)

  25. Topic 1: Memory ManagementWeak References • Types w.r.t. ressurection • Short week references • Long week references • Two different tables in the GC

  26. Topic 1: Memory ManagementGenerations

  27. Topic 1: Memory ManagementLarge Objects Heap • Separate GC Heap • Marked • Sweeped • Never collected • Too costly to move that much data • Monitoring performance under NT

  28. Topic 2:Common Type System 09/06/02

  29. Topic 2: Common Type SystemLooking Back • Why have types at all? • Type-less vs. typed language • Type vs. instance • Each language brings its own type system • Different types on different platforms • Need for common types for interoperation • IDL uses smallest common denominator

  30. Topic 2: Common Type SystemThe Unknown Type • What is a “Type” in the Object Oriented World? • Allowable values • Operations defined • Notions in the Common Type System: • Types are different • ...if they have different representations • Types implement the same interface • ...if they responds to the same set of messages • Types are identical • ...if they have the same representation • ...and respond to the same messages

  31. Topic 2: Common Type SystemLocations • Values are stored in locations • Local variables • Parameters • A storage place with a name • A location can hold a single value at a time • Locations have a well defined type • Type defines which values can be stored • The value must be assignment compatible to the location • Type defines usage of value

  32. Topic 2: Common Type SystemContracts • Specify requirements on implementation of a type • Type states which contracts must be supported • Contracts are shared assumptions on set of signatures • Signatures define constraints on... • Types, locations, parameters, methods, etc • Define which values can be stored • Enumerate allowed operations • Signatures are the enforceable part of a contract • Implementation of a type can be verified

  33. Topic 2: Common Type SystemCoercion • Assignment incompatible value must be converted • Widening coercion • Never loses information • Usually implemented as implicit conversion • Narrowing coercion • Information might be lost • Usually implemented as explicit conversion • Coercion changes the value

  34. Topic 2: Common Type SystemDefining Conversions class Point { public int x, y; public static implicit operator Rectangle (Point p) { Rectangle r = new Rectangle(); r.UL = r.LR = p; return r; } } class Rectangle { public Point UL, LR; }

  35. Topic 2: Common Type SystemCasting • A value has the type of its location • Casting allows use of value as if it had different type • Usually casting is a compile time operation • Unless exact type of value is unknown • Runtime check might result in exception • Casting does not change the value or its type

  36. Topic 2: Common Type SystemCLS • Set of rules for interoperability • „Subset“ of the Common Type System • Large enough to be expressive • Small enough that all languages can accommodate it • Guideline was only to include verifiable constructs • Only applies to types that are externally visible • Assumes assemblies as subjects of interoperability • Identifiers must follow certain rules • Case sensitivity

  37. Topic 2: Common Type SystemTypology • Value types • Represented by sequence of bits in a location • Common built-in data types • Reference types • Represented by a location and a sequence of bits • Objects, Interfaces, Pointers

  38. Topic 2: Common Type SystemBuild-in Value Types • Integer values • int8, int16, int32, int64 • unsigned counterparts • Super long decimal value • decimal (28 digits) • Floating point values • float32, float64 • Unicode character value • char • Boolean value • bool

  39. Topic 2: Common Type SystemBuild-in Reference Types • Object • Base class for all types • Allows for polymorphism across all types • String • Can hold up to 231 characters • Is immutable • Changing creates new modified string

  40. 42 42 42 Boxed: Reference Unboxed: Copy Topic 2: Common Type SystemBoxing and Unboxing • Value types can be boxed and unboxed • Boxing allows value types to travel by-ref • Based on object-ness of all types double Value; // Boxing object BoxedValue = Value;// UnboxingValue = (double)BoxedValue;

  41. Topic 2: (continued)Common Type System 09/09/02

  42. Topic 2: Common Type SystemExceptions • When exception occurs an object is created • Subclass of System.Exception • Protected block for exception handling : try • Protected blocks may be nested • If exception occurs CLR searches for handler • Four kinds of handlers: • Catch handler filters type of exception object • Filter handler determines if exception can be handled • Fault handler executes when exception occurs • Finally handler executes whenever protected block is left

  43. Topic 2: Common Type SystemDelegates & Events • Delegates • Similar to function pointers found in C, C++ • Use is type safe • Multicast delegates call more than one method • Derive from System.MulticastDelegate • Result of Combine method is MulticastDelegate to call • Events • Change of state of an object • Observer registers delegate with event as handler • Event triggers MulticastDelegate when it is fired

  44. Topic 2: Common Type SystemDelegates Example public delegate int operation (int x, int y); int Add (int x, int y) { return x + y; } void PrintResult (int x, int y, operation o) { Console.WriteLine(o(x, y)); } void Run () { PrintResult(4, 7, new operation(Add)); }

  45. Topic 2: Common Type SystemEvents Example delegate void Listener (object o); event Listener OnSomethingHeard; void SomethingHeard (object o) { OnSomethingHeard(o); } void SimpleListener (object o) { Console.WriteLine(o); } void AddListener () { OnSomethingHeard += new Listener(SimpleListener); }

  46. Topic 2: Common Type SystemAttributes • User-defined annotations to the metadata • An instance of a type is stored along with metadata • Declarative access to functionality • Can be of any type • Mostly derived from System.Attribute • CLR predefines some attribute types • Control of runtime behavior

  47. Topic 2: (continued)Common Type System 09/11/02

  48. Topic 2: Common Type SystemPointers • Pointer contains address of memory location • Pointers are typed • Defined by specifying location signature • Type safe operations defined • Loading the value from the location • Storing assignment compatible value to the location • Address arithmetic is considered type unsafe • Such unmanaged pointers are not part of the CLS

  49. Topic 2: Common Type SystemType Members • Allowable values of type may have substructure • Representation may be subdivided • Named sub-values are called fields • Type is called compound type • Indexed sub-values are called array elements • Type is called array • Each field or element is typed • Array elements all have same type • These types do never change • Type may declare static fields • Locations associated with type – not with instance

  50. Topic 2: Common Type SystemType Members (cont.) • Methods are operations • Defined to operate on the type: static method • Defined operate on an instance • Method is passed the instance to operate on : this • Instance vs. virtual method • Both methods may be overridden • Instance method is called on declared type • Determined at compile time • Virtual method is called on exact type • Determined at runtime

More Related