860 likes | 1.04k Views
Introduction to .Net/C#. By Oliver Feb 23, 2011. Outline. Introduction to .NET Introduction to C# Data Type Array Property Flow control Exception handler Hello world and debug. Microsoft .NET. .NET initiative Introduced by Microsoft (June 2000)
E N D
Introduction to .Net/C# By Oliver Feb 23, 2011
Outline • Introduction to .NET • Introduction to C# • Data Type • Array • Property • Flow control • Exception handler • Hello world and debug
Microsoft .NET • .NET initiative • Introduced by Microsoft (June 2000) • Vision for embracing the Internet in software development • Independence from specific language or platform • Applications developed in any .NET-compatible language • Visual Basic.NET, Visual C++.NET, C# and more • Supports portability and interoperability • Architecture capable of existing on multiple platforms • Supports portability
Microsoft .NET • Key components of .NET • Web services • Applications used over the Internet • Software reusability • Web services provide solutions for variety of companies • Cheaper than one-time solutions that can’t be reused • Single applications perform all operations for a company via various Web services • Manage taxes, bills, investments and more • Pre-packaged components using Visual Programming • (buttons, text boxes, scroll bars) • Make application development quicker and easier
Microsoft .NET • Keys to interaction • XML (Extreme Markup Language) and SOAP (Simple Object Access Protocol) • “Glue” that combines various Web services to form applications • XML gives meaning to data • SOAP allows communication to occur easily
Microsoft .NET • RTM: • 2002(v1.0) • 2003 (v1.1) • 2005 (v2.0) • 2006 (v3.0) • 2007 (v3.5) • 2010 (v4.0) • …
.NET Framework • .NET Framework • Heart of .NET strategy • Manages and executes applications and Web services • Provides security, memory management and other programming capabilities • Includes Framework Class Library (FCL) • Pre-packaged classes ready for reuse • Used by any .NET language • Details contained in Common Language Specification (CLS) • Submitted to European Computer Manufacturers Association to make the framework easily converted to other platforms • Executes programs by Common Language Runtime (CLR)
CommonLanguageRuntime(CLR) Legacy Software(unmanaged code) Managed Executable Reusable Managed Components Common Language Runtime(JIT compilation, memory management, etc.) Windows (or other operating oystem)
CommonLanguageRuntime(CLR) • Why two compilations? • Platform independence • .NET Framework can be installed on different platforms • Execute .NET programs without any modifications to code • .NET compliant program translated into platform independent MSIL • Language independence • MSIL form of .NET programs not tied to particular language • Programs may consist of several .NET-compliant languages • Old and new components can be integrated • MSIL translated into platform-specific code • Other advantages of CLR • Execution-management features • Manages memory, security and other features • Relieves programmer of many responsibilities • More concentration on program logic
Assembly Language Compiler Native Code JIT Compiler Execution CompilationAndExecution Compilation Code (IL) Source Code Metadata At installation or the first time each method is called
JIT • All managed code runs in native machine language • However, all managed code is made up of IL and metadata • The CLR JIT-compiles the IL and metadata • At execution time • Executed directly by CPU • Allows for the best of both worlds • Code management features • Performance of full-speed execution
GarbageCollector • GC is a most important part of CLR • It manages many objects lifetime. • Instead of allocate/delete keywords in C++, objects are automatically deleted when the application no longer needs them. • It’s Important to build a efficiently application.
0.5 2.5 line s Heap Stack GarbageCollector string s; StraighLine line; s = "dog"; line = new StraightLine(0.5, 2.5); "dog"
GarbageCollector • CLR will run GC automatically to free all unreachable objects in heap memory which no references remained.
Free space object5 object1 • banana object6 object2 object4 x … allocated Stack Managed Heap GarbageCollector object3 a … … b … …
Free space object1 object5 object6 x … allocated Stack Managed Heap GarbageCollector object3 … … … … a b
GarbageCollector • GC demo, show GC collect and different result in debug and release mode.
GarbageCollector • GC manages all objects in Heap, but not any objects been allocated on Heap, like: Unmanaged resource, windows handler, DB connection, file handler…therefore, we need use the Dispose pattern to clean up the memory.
GarbageCollector FileStreamfs = new FileStream("Temp.dat", FileMode.Create); try { fs.Write(bytesToWrite, 0, bytesToWrite.Length); } finally { if (fs != null) ((IDisposable)fs).Dispose(); }
GarbageCollector • GC events notification have been added in .Net 4.0.
Summary • CLR will run GC automatically to free all unreachable objects in heap memory which no references remained. • The GC is only called by the CLR when heap memory becomes scarce. • The GC only can collect manage resources, all unmanaged resources need to be collected by programmer. • The GC will reduce memory leak, but not disappeared.
The .NETFrameworkLibrary • Sit on top of the CLR • Reusable types that tightly integrate with the CLR • Object oriented – inheritance, polymorphism, etc. • Provide functionality for ASP.NET, XML Web Services, ADO.NET, Windows Forms, basic system functionality (IO, XML, etc.)
System.Web System.Windows.Forms Design ComponentModel Services UI Description HtmlControls Discovery WebControls Protocols System.Drawing Caching Security Drawing2D Printing Configuration SessionState Imaging Text System.Data System.Xml OleDb SqlClient XSLT Serialization Common SQLTypes XPath System Collections IO Security Runtime InteropServices Configuration Net ServiceProcess Remoting Diagnostics Reflection Text Serialization Globalization Resources Threading The .NETFrameworkLibrary
Base Framework Collections Security Configuration ServiceProcess Diagnostics Text Globalization Threading IO Runtime Net InteropServices Reflection Remoting Serialization Resources
Summary .NET Framework is a code execution platform .NET Framework consists of two primary parts: .NET Class Libraries, Common Language Runtime All CLR-compliant compilers support the common type system Managed code is object oriented Managed code is compiled to and assembly (MSIL) by language specific compiler Assemblies are compiled to native code by JIT compiler
.NETandC# • .NET platform • Web-based applications can be distributed to variety of devices and desktops • C# • Developed specifically for .NET • Enable programmers to migrate from C/C++ and Java easily • Event-driven, fully OO, visual programming language • Has IDE • Process of rapidly creating an application using an IDE is called Rapid Application Development (RAD)
C# • Language interoperability • Can interact with software components written in different languages or with old packaged software written in C/C++ • Can interact via internet, using industry standards (SOAP and XML) • Simple Object Access Protocol - Helps to share program “chunks” over the internet • Accommodates a new style of reusable programming in which applications are created from building blocks
Value & Reference Types • ctor • Value type always have a default value • Reference type can be null int x; MyClass obj; x =0 obj is null
Value & Reference Types • Memory allocation • Reference type always allocate in heap • Value type always be allocated in a place where its been declared int x; MyClass obj; obj = new MyClass(); Allocate a variable on stack Allocate a variable on stack Allocate the object on heap
0.5 2.5 obj x Heap Stack Value & Reference Types
Value & Reference Types • Copy int x; MyClass obj; obj = new MyClass(); Int y = x; MyClass objCopy = obj; deep copy shallow copy
Value & Reference Types • Memory Disposal • Once the method has finished running, its local stack-allocated variable, x, obj, will disappear from scope and be “popped” off the stack. • GC will automatically deallocate it from the heap some times later. GC will know to delete it, because the object has no valid referee (one whose chain of reference originates back to a stack-allocated object). • C++ programmers may be a bit uncomfortable with this and may want to delete the object anyway (just to be sure!) but in fact there is no way to delete the object explicitly. We have to rely on the CLR for memory disposal—and indeed, the whole .NET framework does just that!
TypeExample • An example of using types in C# • declare before you use (compiler enforced) • initialize before you use (compiler enforced) public class App { public static void Main() { int width, height; width = 2; height = 4; int area = width * height; int x; int y = x * 2; ... } } declarations decl + initializer error, x not set
Typeconversion • Some automatic type conversions available • from smaller to larger types • Otherwise you need a cast or an explicit conversion… • typecast syntax is type name inside parentheses • conversion based on System.Convert class
Typeconversion int i = 5; double d = 3.2; string s = "496"; d = i; i = (int) d; i = System.Convert.ToInt32(s); implicit conversion typecast required conversion required
BoxingandUnboxing • Boxing • Automatic conversion of a value-type in a reference-type • Like: • Unboxing • Conversion of a reference-type into a value-type • Like: Object o = 25; inti= (int)o;
Boxing and Unboxing • Boxing • Memory is allocated from the managed heap. • The value type’s fields are copied to the newly allocated heap memory • The address of the object is returned. This address is now a reference to an object
BoxingandUnboxing • Performance • If boxing occurs frequently, it will wastes memory and hurts performance. • Because many small objects will be created on heap, and waiting be clean up by GC • Instead, we often use generics method or delegate.
String • How to create a string object. • String’s performance • StringBuilder object • String encoding
String string s = "496"; String ss = “adasdc”; Create String object is immutable. That is, once created, a string can never get longer, get shorter, or have any of its characters changed.
String string s = "496"; String ss = “adasdc”; String text = s + ” and ” + ss + “ and …”; Bad performance because it creates multiple string objects on the garbage-collected heap.
String StringBuilder sbText= new stringBuilder(); sbText.append(s); sbText.append(“ and ”); sbText.append(ss); sbText.append(“ and… ”); string text = sbText.ToString();
String OR: string text = String.Format(“{0} and {1} and…”, s, ss); Because String.Format() method be implemented by StringBuilder operations.
String • Encoding • Demo
Collections • Array • Queue • Stack • HashTable • List<T> • Dictionary<Tkey,Tvalue> …
Arrays • Arrays are reference types • assigned default values (0 for numeric, null for references, etc.) int[] a; a = new int[5]; a[0] = 17; a[1] = 32; int x = a[0] + a[1] + a[4]; int l = a.Length; create element access number of elements
Queue • Use Queue to implement a First-In, First-Out type (FIFO) type of collection: create Queue myQ = new Queue(); myQ.Enqueue( new Robin( 8 ) ); myQ.Enqueue( new BlueJay( 14 ) ); ((Bird)myQ.Dequeue()).Speak(); ((Bird)myQ.Dequeue()).Speak(); insert an element pop an element