1、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,.NET initiative Introduced by Microsoft (June 2000) Vision for embracing the Internet in software development Independence from
2、 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
3、Applications used over the Internet Software reusability Web services provide solutions for variety of companies Cheaper than one-time solutions that cant be reused Single applications perform all operations for a company via various Web services Manage taxes, bills, investments and more Pre-package
4、d 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 m
5、eaning to data SOAP allows communication to occur easily,Microsoft .NET,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 manage
6、ment and other programming capabilitiesIncludes Framework Class Library (FCL) Pre-packaged classes ready for reuse Used by any .NET languageDetails contained in Common Language Specification (CLS) Submitted to European Computer Manufacturers Association to make the framework easily converted to othe
7、r platformsExecutes programs by Common Language Runtime (CLR),Windows (or other operating oystem),Common Language Runtime (JIT compilation, memory management, etc.),Legacy Software (unmanaged code),Managed Executable,Reusable Managed Components,Common Language Runtime (CLR),Why two compilations? Pla
8、tform 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
9、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,Com
10、mon Language Runtime (CLR),Compilation And Execution,Source Code,Compilation,At installation or the first time each method is called,Code (IL),Metadata,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
11、 execution time Executed directly by CPU Allows for the best of both worlds Code management features Performance of full-speed execution,JIT,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 appl
12、ication no longer needs them. Its Important to build a efficiently application.,Garbage Collector,string s;StraighLine line;s = “dog“; line = new StraightLine(0.5, 2.5);,“dog“,Garbage Collector,CLR will run GC automatically to free all unreachable objects in heap memory which no references remained.
13、,Garbage Collector,object3,a,b, , ,Garbage Collector,object3,a,b, , ,Garbage Collector,GC demo, show GC collect and different result in debug and release mode.,Garbage Collector,GC manages all objects in Heap, but not any objects been allocated on Heap, like: Unmanaged resource, windows handler, DB
14、connection, file handlertherefore, we need use the Dispose pattern to clean up the memory.,Garbage Collector,FileStream fs = new FileStream(“Temp.dat“, FileMode.Create);tryfs.Write(bytesToWrite, 0, bytesToWrite.Length);finallyif (fs != null)(IDisposable)fs).Dispose();,Garbage Collector,GC events not
15、ification have been added in .Net 4.0.,Garbage Collector,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
16、to be collected by programmer. The GC will reduce memory leak, but not disappeared.,Summary,The .NET Framework Library,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
17、, Windows Forms, basic system functionality (IO, XML, etc.),The .NET Framework Library,Threading,Text,ServiceProcess,Security,Resources,Reflection,Net,IO,Globalization,Diagnostics,Configuration,Collections,Serialization,Remoting,InteropServices,Runtime,Base Framework,.NET Framework is a code executi
18、on 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
19、native code by JIT compiler,Summary,.NET and C#,.NET platform Web-based applications can be distributed to variety of devices and desktopsC# 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
20、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
21、) Simple Object Access Protocol - Helps to share program “chunks” over the internetAccommodates a new style of reusable programming in which applications are created from building blocks,Data Types/Arrays,Mapping C# to CTS,Value & Reference Types,ctor Value type always have a default value Reference
22、 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 the object on heap,A
23、llocate a variable on 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, w
24、ill 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 uncom
25、fortable 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 disposaland indeed, the whole .NET framework does just that!,Type Example,An example of using types in C# declare before y
26、ou 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,Type conversion,Some automatic type conversions
27、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,Type conversion,int i = 5; double d = 3.2; string s = “496“;d = i;i = (int) d;i = System.Convert.ToInt32(s);,implicit co
28、nversion,typecast required,conversion required,Boxing and Unboxing,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;,int i= (int)o;,Boxing and Unboxing,Boxing Memory is allocated from the managed heap.
29、 The value types 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,Boxing and Unboxing,Performance If boxing occurs frequently, it will wastes memory and hurts performance. Because many small objects will be creat
30、ed on heap, and waiting be clean up by GC Instead, we often use generics method or delegate.,String,How to create a string object. Strings performance StringBuilder object String encoding,String,string s = “496“; String ss = “adasdc”;,Create,String object is immutable. That is, once created, a strin
31、g 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
32、(); sbText.append(s); sbText.append(“ and ”); sbText.append(ss); sbText.append(“ and ”); string text = sbText.ToString();,String,string text = String.Format(“0 and 1 and”, s, ss);,Because String.Format() method be implemented by StringBuilder operations.,OR:,String,Encoding Demo,Collections,Array Qu
33、eue Stack HashTable List Dictionary ,Arrays,Arrays are reference types assigned default values (0 for numeric, null for references, etc.),int a; a = new int5;a0 = 17; a1 = 32; int x = a0 + a1 + a4;int l = a.Length;,element access,create,number of elements,Queue,Use Queue to implement a First-In, Fir
34、st-Out type (FIFO) type of collection:,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,create,pop an element,Stack,Use Stack to implement a Last-In, First-Out type (LIFO) type of collec
35、tion:,Stack myStack = new Stack();myStack.Push( new Robin( 8 ) );myStack.Push( new BlueJay( 14 ) );(Bird)myStack.Pop().Speak(); (Bird)myStack.Pop().Speak();,insert an element,create,pop an element,HashTable,Use Hashtable to implement a dictionary type of collection:,Hashtable myHT = new Hashtable();
36、myHT“Robin“ = new Robin( 8 );myHT“BlueJay“ = new BlueJay( 14 );(Bird)myHT“BlueJay“).Speak();,insert an element,create,use an element,List,Its the most commonly collection type, use List to implement a Robin collection :,List myList= new List ();myList.Add( new Robin ( 8 ); myList.Add( new Robin ( 10
37、 );foreach (Robin obj in myList) obj.Speak(); ,insert an element,create,use an element,Dictionary,Its the most commonly collection type, use List to implement a Robin Dictionary:,Dictionary myDic= new Dictionary();string sarah = “ Sarah “; string harold= “ harold “;myDic.Add(sarah , new Robin ( 8 );
38、 myDic.Add(harold , new Robin ( 10 );if (myDic.ContainsKey(sarah)myDicsarah.Speak();,insert an element,create,use an element,Dictionary VS Hashtable,Dictionary is used in signal threaded application.Hashtable is a thread safe type, it also can be used in multi-threaded application.Hashtable table=Ha
39、shtable.Synchronized(new Hashtable();,Properties,Instead expose a field, in C#, we usually use get/set to expose a property of class. Like:,using System; class MyClassk int _integer; public int Integer get return _integer; set _integer = value; ,Define a Property,Get method block,Set method block,Pr
40、operties,After compilation, we can got the following code from IL,class MyClassk int _integer; public int get_Integer() return _integer; public void set_Integer( int value) _integer = value; ,Get method,Set method,Properties,To avoid the data be destroyed, we can make a read only property :,using Sy
41、stem; class MyClassk int _integer; public int Integer get return _integer; ,Define a Property,Get method block,Properties,Property has all features of method,using System; class MyClassk int _integer; public virtual int Integer get return _integer; protected set _integer = value; ,define a virtual P
42、roperty,get method block,access modifiers,Properties,Enhanced features of Interface, more component-oriented,using System; Interface INameValuePair string Name get; Object Value get;set; ,define an interface,define a Property,Properties Summary,More component-oriented Accommodate the changes of the
43、feature JIT often use code inline to speed up application Code snippet let coding properties more easy.,Iteration & Flow Control,Iteration Constructs Flow Control,Iteration Constructs,Loop over data for foreach while do while,Iteration Constructs: for,for (int index = 0; index int.MaxValue; index+)/
44、just do it. ,Iteration Constructs: foreach,List myList= new List ();myList.Add( new Robin ( 8 ); myList.Add( new Robin ( 10 );foreach (Robin obj in myList) obj.Speak(); ,Iteration Constructs: while,int index = 0; while (index int.MaxValue) /just do it. index+; ,check first before running,Iteration C
45、onstructs: do while,int index = 0; Do /just do it. index+; while (index int.MaxValue);,check after the running,first pass always executed,Flow Control,Flow control statements if switch,Flow Control: IF,if (“ = string.Empty) Console.WriteLine(“equal“); else Console.WriteLine(“not equal“); ,Flow Contr
46、ol: IF,if (string.Empty = “”) Console.WriteLine(“equal“); else if (string.Empty = null) Console.WriteLine(“equal N“); else Console.WriteLine(“not equal“); ,Flow Control: switch,Switch(variable) case a:/codebreak;case b:/codebreak;default:/default code or exception ,Numeric and string types are allow
47、ed,Exception Handling,No matter which kind of programming languages, exception handling is always a necessary features. Try-catch Finally Coding practice Performance,Exception Handling,try /remote access. catch (InvalidOperationException ) throw; ,catch,Try-catch Place the sections of code that migh
48、t throw exceptions in a try block and place code that handles exceptions in a catch block,Exception Handling,Incorrect,try /InvalidOperationException catch (InvalidOperationException ex) throw ex; ,It throws the same exception object that it caught and causes the CLR to reset its starting point for
49、the exception:,Exception Handling,finally When an exception occurs, execution stops and control is given to the closest exception handler. This often means that lines of code you expect to always be called are not executed. Some resource cleanup, such as closing a file, must always be executed even if an exception is thrown. To accomplish this, you can use a finally block. A finally block is always executed, regardless of whether an exception is thrown.,