85
Introduction to .Net/C# By Oliver Feb 23, 2011

Introduction to .Net/C#

  • Upload
    dacey

  • View
    78

  • Download
    4

Embed Size (px)

DESCRIPTION

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) - PowerPoint PPT Presentation

Citation preview

Page 1: Introduction to .Net/C#

Introduction to .Net/C#

By Oliver

Feb 23, 2011

Page 2: Introduction to .Net/C#

Outline

Introduction to .NET Introduction to C# Data Type Array Property Flow control Exception handler Hello world and debug

Page 3: Introduction to .Net/C#

.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

Page 4: Introduction to .Net/C#

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

Page 5: Introduction to .Net/C#

Keys to interactionXML (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

Page 6: Introduction to .Net/C#

Microsoft .NET

RTM: 2002(v1.0) 2003 (v1.1) 2005 (v2.0) 2006 (v3.0) 2007 (v3.5) 2010 (v4.0) …

Page 7: Introduction to .Net/C#

.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)

Page 8: Introduction to .Net/C#

Windows (or other operating oystem)

Common Language Runtime(JIT compilation, memory management, etc.)

Legacy Software

(unmanaged code)

Managed ExecutableReusable

Managed Components

Common Language

Runtime (CLR)

Page 9: Introduction to .Net/C#
Page 10: Introduction to .Net/C#

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

Common Language

Runtime (CLR)

Page 11: Introduction to .Net/C#

Compilation And Execution

AssemblyAssemblySource Source CodeCode

Language Language CompilerCompiler

Compilation

At installation or the first time each method is called

Execution

JIT CompilerJIT CompilerNativeNative

CodeCode

Code (IL)Code (IL)

MetadataMetadata

Page 12: Introduction to .Net/C#

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

JIT

Page 13: Introduction to .Net/C#

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.

Garbage Collector

Page 14: Introduction to .Net/C#

string s; StraighLine line; s = "dog"; line = new StraightLine(0.5, 2.5);

StackHeap

sline

"dog"

0.5

2.5

Garbage Collector

Page 15: Introduction to .Net/C#

CLR will run GC automatically to free all unreachable objects in heap memory which no references remained.

Garbage Collector

Page 16: Introduction to .Net/C#

Managed Heap

allocated

Free space

Stack

x

object1

banana

object3

object5

object2

object6

a

b…

……

Garbage Collector

Page 17: Introduction to .Net/C#

Managed Heap

allocated

Free space

Stack

x

object1

object3

object5

object6

a

b

……

Garbage Collector

Page 18: Introduction to .Net/C#

GC demo, show GC collect and different result in debug and release mode.

Garbage Collector

Page 19: Introduction to .Net/C#

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.

Garbage Collector

Page 20: Introduction to .Net/C#

FileStream fs = new FileStream("Temp.dat", FileMode.Create);

try

{

fs.Write(bytesToWrite, 0, bytesToWrite.Length);

}

finally

{

if (fs != null)

((IDisposable)fs).Dispose();

}

Garbage Collector

Page 21: Introduction to .Net/C#

GC events notification have been added in .Net 4.0.

Garbage Collector

Page 22: Introduction to .Net/C#

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.

Summary

Page 23: Introduction to .Net/C#

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, Windows Forms, basic system functionality (IO, XML, etc.)

Page 24: Introduction to .Net/C#

System System System System

System.DataSystem.DataSystem.DataSystem.Data System.XmlSystem.XmlSystem.XmlSystem.Xml

System.WebSystem.WebSystem.WebSystem.Web

GlobalizationGlobalization

DiagnosticsDiagnostics

ConfigurationConfiguration

CollectionsCollections

ResourcesResources

ReflectionReflection

NetNet

IOIO

ThreadingThreading

TextText

ServiceProcessServiceProcess

SecuritySecurity

CommonCommon

OleDbOleDb

SQLTypesSQLTypes

SqlClientSqlClient

XPathXPath

XSLTXSLT

RemotingRemoting

SerializationSerialization

SerializationSerialization

ConfigurationConfiguration SessionStateSessionState

CachingCaching SecuritySecurity

DescriptionDescription

DiscoveryDiscoveryProtocolsProtocols

HtmlControlsHtmlControls

WebControlsWebControls System.DrawingSystem.DrawingSystem.DrawingSystem.Drawing

ImagingImaging

Drawing2DDrawing2D

TextText

PrintingPrinting

System.Windows.FormsSystem.Windows.FormsSystem.Windows.FormsSystem.Windows.Forms

DesignDesign ComponentModelComponentModelUIUI

InteropServicesInteropServicesRuntimeRuntime

ServicesServices

The .NET Framework Library

Author
double check this
Page 25: Introduction to .Net/C#

ThreadingThreading

TextText

ServiceProcessServiceProcess

SecuritySecurity

ResourcesResources

ReflectionReflection

NetNet

IOIO

GlobalizationGlobalization

DiagnosticsDiagnostics

ConfigurationConfiguration

CollectionsCollections

SerializationSerialization

RemotingRemoting

InteropServicesInteropServices

RuntimeRuntime

Base Framework

Author
double check this
Page 26: Introduction to .Net/C#

.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

Summary

Page 27: Introduction to .Net/C#

.NET and C#

.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)

Page 28: Introduction to .Net/C#

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

Page 29: Introduction to .Net/C#

Data Types/Arrays

St r i ng Ar r ay Val ueType Except i on Del egat e Cl ass1

Mul t i castDel egat e

Cl ass2

Cl ass3

Obj ect

Enum1

St r uct ur e1EnumPr i mi t i ve t ypes

Bool ean

Byt e

I nt 16

I nt 32

I nt 64

Char

Si ngl e

Doubl e

Deci mal

Dat eTi me

System-defined types

User-defined types

Del egat e1

Ti meSpan

Gui d

Page 30: Introduction to .Net/C#

Mapping C# to CTS

Keyword Description Special format for literalsbool Boolean true false

char 16 bit Unicode character 'A' '\x0041' '\u0041'

sbyte 8 bit signed integer none

byte 8 bit unsigned integer none

short 16 bit signed integer none

ushort 16 bit unsigned integer none

int 32 bit signed integer none

uint 32 bit unsigned integer U suffix

long 64 bit signed integer L or l suffix

ulong 64 bit unsigned integer U/u and L/l suffix

float 32 bit floating point F or f suffix

double 64 bit floating point no suffix

decimal 128 bit high precision M or m suffix

string character sequence "hello", @"C:\dir\file.txt"

Page 31: Introduction to .Net/C#

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

Page 32: Introduction to .Net/C#

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

Allocate a variable on stack

Page 33: Introduction to .Net/C#

Value & Reference Types

StackHeap

xobj

0.5

2.5

Page 34: Introduction to .Net/C#

Value & Reference Types

Copy

int x;

MyClass obj;obj = new MyClass();

Int y = x;

MyClass objCopy = obj;

deep copy

shallow copy

Page 35: Introduction to .Net/C#

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!

Page 36: Introduction to .Net/C#

Type Example

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

Page 37: Introduction to .Net/C#

Type conversion

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

Page 38: Introduction to .Net/C#

Type conversion

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

Page 39: Introduction to .Net/C#

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;

Page 40: Introduction to .Net/C#

Boxing and Unboxing

BoxingMemory is allocated from the

managed heap. The value type’s fields are copied to

the newly allocated heap memoryThe address of the object is returned.

This address is now a reference to an object

Page 41: Introduction to .Net/C#

Boxing and Unboxing

PerformanceIf 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.

Page 42: Introduction to .Net/C#

String

How to create a string object. String’s performance StringBuilder object String encoding

Page 43: Introduction to .Net/C#

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.

Page 44: Introduction to .Net/C#

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.

Page 45: Introduction to .Net/C#

String

StringBuilder sbText= new stringBuilder();sbText.append(s);sbText.append(“ and ”);sbText.append(ss);sbText.append(“ and… ”);string text = sbText.ToString();

Page 46: Introduction to .Net/C#

String

string text = String.Format(“{0} and {1} and…”, s, ss);

Because String.Format() method be implemented by StringBuilder operations.

OR:

Page 47: Introduction to .Net/C#

String

EncodingDemo

Page 48: Introduction to .Net/C#

Collections

Array Queue Stack HashTable List<T> Dictionary<Tkey,Tvalue>

Page 49: Introduction to .Net/C#

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;

element access

create

number of elements

Page 50: Introduction to .Net/C#

Queue

Use Queue to implement a First-In, First-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

Page 51: Introduction to .Net/C#

Stack

Use Stack to implement a Last-In, First-Out type (LIFO) type of collection:

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

Page 52: Introduction to .Net/C#

HashTable

Use Hashtable to implement a dictionary type of collection:

Hashtable myHT = new Hashtable();

myHT["Robin"] = new Robin( 8 );myHT["BlueJay"] = new BlueJay( 14 );

((Bird)myHT["BlueJay"]).Speak();

insert an element

create

use an element

Page 53: Introduction to .Net/C#

List<T>

It’s the most commonly collection type, use List<T> to implement a Robin collection :

List<Robin> myList= new List<Robin> ();

myList.Add( new Robin ( 8 );myList.Add( new Robin ( 10 );

foreach (Robin obj in myList) {

obj.Speak();}

insert an element

create

use an element

Page 54: Introduction to .Net/C#

Dictionary<Tkey,Tvalue>

It’s the most commonly collection type, use List<T> to implement a Robin Dictionary:

Dictionary<string,Robin> myDic= new Dictionary<string,Robin>();

string sarah = " Sarah ";string harold= " harold ";

myDic.Add(sarah , new Robin ( 8 );myDic.Add(harold , new Robin ( 10 );

if (myDic.ContainsKey(sarah)) {

myDic[sarah].Speak(); }

insert an element

create

use an element

Page 55: Introduction to .Net/C#

Dictionary VS Hashtable

Dictionary<K,V> is used in signal threaded application.

Hashtable is a thread safe type, it also can be used in multi-threaded application.

Hashtable table=Hashtable.Synchronized(new Hashtable());

Page 56: Introduction to .Net/C#

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

Page 57: Introduction to .Net/C#

Properties

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

Page 58: Introduction to .Net/C#

Properties

To avoid the data be destroyed, we can make a read only property :

using System; class MyClassk{ int _integer;

public int Integer { get {return _integer;}

} }

Define a Property

Get method block

Page 59: Introduction to .Net/C#

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 Property

get method block

access modifiers

Page 60: Introduction to .Net/C#

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

Page 61: Introduction to .Net/C#

Properties Summary

More component-oriented Accommodate the changes of the feature JIT often use code inline to speed up application Code snippet let coding properties more easy.

Page 62: Introduction to .Net/C#

Iteration & Flow Control

Iteration Constructs Flow Control

Page 63: Introduction to .Net/C#

Iteration Constructs

Loop over dataforforeachwhiledo while

Page 64: Introduction to .Net/C#

Iteration Constructs: for

for (int index = 0; index < int.MaxValue; index++) { //just do it... }

Page 65: Introduction to .Net/C#

Iteration Constructs: foreach

List<Robin> myList= new List<Robin> ();

myList.Add( new Robin ( 8 );myList.Add( new Robin ( 10 );

foreach (Robin obj in myList) {

obj.Speak();}

Page 66: Introduction to .Net/C#

Iteration Constructs: while

int index = 0;while (index < int.MaxValue){

//just do it... index++;}

check first before running

Page 67: Introduction to .Net/C#

Iteration Constructs: do while

int index = 0;Do{ //just do it...

index++;} while (index < int.MaxValue);

check after the running

first pass always executed

Page 68: Introduction to .Net/C#

Flow Control

Flow control statementsifswitch

Page 69: Introduction to .Net/C#

Flow Control: IF

if ("" == string.Empty)

{

Console.WriteLine("equal");

}

else

{

Console.WriteLine(“not equal");

}

Page 70: Introduction to .Net/C#

Flow Control: IF

if (string.Empty == “”)

{

Console.WriteLine("equal");

}

else if (string.Empty == null)

{

Console.WriteLine(“equal N");

}

else

{

Console.WriteLine(“not equal");

}

Page 71: Introduction to .Net/C#

Flow Control: switch

Switch(variable)

{

case a:

//code

break;

case b:

//code

break;

default:

//default code or exception

}

Numeric and string types are allowed

Page 72: Introduction to .Net/C#

Exception Handling

No matter which kind of programming languages, exception handling is always a necessary features.Try-catchFinallyCoding practice Performance

Page 73: Introduction to .Net/C#

Exception Handling

try {

//remote access.}catch (InvalidOperationException ){

throw;}

catch

Try-catch Place the sections of code that might throw exceptions in a try

block and place code that handles exceptions in a catch block

Page 74: Introduction to .Net/C#

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 the exception:

Page 75: Introduction to .Net/C#

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.

Page 76: Introduction to .Net/C#

Exception HandlingFileStream fs = null; try {

fs = new FileStream(@"C:\temp\data.txt", FileMode.Open); StreamReader sr = new StreamReader(fs);

string line; line = sr.ReadLine(); Console.WriteLine(line); }

catch (FileNotFoundException e) {

throw new NameNotFoundException(@"[data.txt not in c:\temp directory]",e); } catch (IOException e) {

throw new NameNotFoundException(@"[data.txt not in c:\temp directory]",e); } finally { if (fs != null) fs.Close(); }

finally

try

catch

catch

Page 77: Introduction to .Net/C#

Exception Handling

public class EmployeeListNotFoundException: Exception {

public EmployeeListNotFoundException() { }

public EmployeeListNotFoundException(string message) : base(message) { }

public EmployeeListNotFoundException(string message, Exception inner) : base(message, inner) { }

}

User-defined exception

Page 78: Introduction to .Net/C#

Best Practice add more friendly information to an

exception when thrown, like parameters… Never throw an Exception type error, use a

more meaningful exception type instead. Don’t catch everything Never ignore any exception

Exception Handling

Page 79: Introduction to .Net/C#

Exception Handling

This code indicates that it was expecting any and all exceptions and knows how to recover

from any and all situations. How can this possibly be?

Incorrect

try {

// try to execute code that the programmer knows might fail...

}

catch (Exception) {

...

}

Page 80: Introduction to .Net/C#

Exception Handling

FileStream fs = new FileStream("Temp.dat", FileMode.Create);

try

{

fs.Write(bytesToWrite, 0, bytesToWrite.Length);

}

finally

{

if (fs != null)

((IDisposable)fs).Dispose();

}

Page 81: Introduction to .Net/C#

Exception Handling

using (FileStream fs = new FileStream("Temp.dat", FileMode.Create))

{

fs.Write(bytesToWrite, 0, bytesToWrite.Length);

}

Page 82: Introduction to .Net/C#

Exception Handling

PerformanceIf an exception occurs frequently,

performance hit of throwing and catching the exceptions was taking a large toll on the application’s overall performance.

Page 83: Introduction to .Net/C#

Exception Handling

Debugging Run the DEMO and show how to

debugging exception in Visual studio 2010.

Page 84: Introduction to .Net/C#

Exception Handling

static void Main(string[] args) { try { InternalMethod(); } catch (InvalidOperationException ex) {

Console.WriteLine(ex.Message); } } static void InternalMethod() { try { throw new InvalidOperationException ("try"); } finally { Console.WriteLine("exception finally"); } }

What’s the result?

Page 85: Introduction to .Net/C#

Hello world

Create a DEMO and debug