The document provides an introduction to .NET including:
- The goals of the .NET framework which include improved development, deployment, and execution.
- An overview of the .NET platform and framework including the common language runtime, base class library, and support for multiple languages.
- A brief description of C# as a managed code programming language that is part of the .NET framework.
2. Session PrerequisitesSession Prerequisites
• This session assumes that you familiarThis session assumes that you familiar
with:with:
– Component-Based or Object-OrientedComponent-Based or Object-Oriented
DevelopmentDevelopment
– Java, Visual C++ or Visual BasicJava, Visual C++ or Visual Basic
programming languageprogramming language
3. AgendaAgenda
• .NET Framework.NET Framework
– GoalsGoals
– .NET Platform.NET Platform
– .NET Compact Framework.NET Compact Framework
• C#C#
– What is C#What is C#
– The Development of C#The Development of C#
4. .NET Framework.NET Framework
GoalsGoals
• DevelopmentDevelopment
– First-class support for componentsFirst-class support for components
– Standard class frameworkStandard class framework
– Automatic memory managementAutomatic memory management
– Consistent error handlingConsistent error handling
– Mixed language applicationsMixed language applications
– Multiple platformsMultiple platforms
– Safer executionSafer execution
• DeploymentDeployment
– Removal on registration dependencyRemoval on registration dependency
– Safety – fewer versioning problemsSafety – fewer versioning problems
– The end of ‘DLL Hell’The end of ‘DLL Hell’
5. .NET Platform.NET Platform
•.NET experiences are XML Web.NET experiences are XML Web
services that allow you to accessservices that allow you to access
information across the Internet andinformation across the Internet and
from standalone applications in anfrom standalone applications in an
integrated way.integrated way.
•Some of the products that MicrosoftSome of the products that Microsoft
is transitioning into .NETis transitioning into .NET
experiences are MSN, bCentral,experiences are MSN, bCentral,
PassportPassport
•Clients are all smart devices such as
PCs, laptops, workstations, phones,
handheld computers
•Some of the .NET client software
Microsoft will offer are Windows CE,
Windows Embedded, Window 2000,
Windows XP, Windows Server 2003
•A core set of building block
services that perform routine tasks
and act as the backbone for
developers to build upon.
•.NET My Services(HailStorm)
•Microsoft Windows Server 2003
•Microsoft Application Center 2000
•Microsoft BizTalk™ Server 2000
•Microsoft Commerce Server 2000
•Microsoft Content Management Server 2001
•Microsoft Exchange Server 2000
•Microsoft Host Integration Server 2000
•Microsoft Internet Security and Acceleration
Server 2000
•Microsoft Mobile Information 2001 Server
•Microsoft SharePoint™ Portal Server 2001
•Microsoft SQL Server™ 2000
•The Microsoft .NET Framework
SDK
•Microsoft Visual Studio.NET 2002
•Microsoft Visual Studio.NET 2003
6. The .NET FrameworkThe .NET Framework
Operating SystemOperating System
Common Language RuntimeCommon Language Runtime
Base Class LibraryBase Class Library
ADO.NET and XMLADO.NET and XML
ASP.NETASP.NET
Web Forms, Web Services,Web Forms, Web Services,
Mobile Web ApplicationMobile Web Application
WindowsWindows
FormsForms
Common Language SpecificationCommon Language Specification
VBVB C++C++ C#C# JScriptJScript ……
VisualStudio.NETVisualStudio.NET
7. .NET Framework and CLR.NET Framework and CLR
CLR Execution ModelCLR Execution Model
VBVBSourceSource
codecode
CompilerCompiler
C++C++C#C#
CompilerCompilerCompilerCompiler
AssemblyAssembly
IL CodeIL Code
AssemblyAssembly
IL CodeIL Code
AssemblyAssembly
IL CodeIL Code
Operating System ServicesOperating System Services
Common Language RuntimeCommon Language Runtime
JIT CompilerJIT Compiler
Native CodeNative Code
ManagedManaged
codecode
UnmanagedUnmanaged
ComponentComponent
8. The .NET Compact FrameworkThe .NET Compact Framework
• .NET will also be available on devices.NET will also be available on devices
– Cell phones, PDAs, others...Cell phones, PDAs, others...
• .NET Compact Framework will be....NET Compact Framework will be...
– FamiliarFamiliar
– Modular—only use pieces you needModular—only use pieces you need
– ExtensibleExtensible
– Cross-processorCross-processor
– Run on multiple OSesRun on multiple OSes
• Not just Windows CENot just Windows CE
9. The .NET Framework Class LibraryThe .NET Framework Class Library
• Accessible from any language targeting the CLRAccessible from any language targeting the CLR
• Written in C#Written in C#
• Organized into namespacesOrganized into namespaces
– All of which are below the System namespaceAll of which are below the System namespace
• Contains:Contains:
– ASP.NETASP.NET
– ADO.NETADO.NET
– Windows FormsWindows Forms
– Much, much moreMuch, much more
10. Common Type SystemCommon Type System
• Every languages that is CLS complianceEvery languages that is CLS compliance
use the same type that use through all theuse the same type that use through all the
frameworkframework
• This Type which is targeted by .NETThis Type which is targeted by .NET
compilers called Common Type Systemcompilers called Common Type System
• This makes sure that every type isThis makes sure that every type is
supported cross-language developmentsupported cross-language development
11. Unified Type SystemUnified Type System
• Traditional views of primitive typesTraditional views of primitive types
– C++, Java: They’re “magic”C++, Java: They’re “magic”
– Smalltalk, Lisp: They’re full-blown objectsSmalltalk, Lisp: They’re full-blown objects
• C# unifies with no performance costC# unifies with no performance cost
– Value types, boxing and unboxingValue types, boxing and unboxing
– Deep simplicity throughout systemDeep simplicity throughout system
• Improved extensibility and reusabilityImproved extensibility and reusability
– New primitive types: Decimal, SQL…New primitive types: Decimal, SQL…
– Collections, etc., work for all typesCollections, etc., work for all types
12. Illustrating the CTSIllustrating the CTS
Object
ValueType
Boolean
Byte
Char
Decimal
Double
Int16
Int32
Single
Int64
UInt16
UInt32
UInt64
Class
String
Array
Interface
Delegate
Value Types
Enum
Structure
Others Others
13. Value and Reference TypesValue and Reference Types
• Value typesValue types
– Variables directly contain dataVariables directly contain data
– Cannot be nullCannot be null
• Reference typesReference types
– Variables contain references to objectsVariables contain references to objects
– May be nullMay be null
int i = 123;int i = 123;
string s = "Hello world";string s = "Hello world";123123ii
ss "Hello world""Hello world"
14. Common Type SystemCommon Type System
• Conversion between each type:Conversion between each type:
Boxing ConversionBoxing Conversion
Convert Value Type to Reference TypeConvert Value Type to Reference Type
.NET creates appropriate dynamic type.NET creates appropriate dynamic type
to “box” the value type.to “box” the value type.
int i = 100;int i = 100;
object o = i;object o = i;
15. Common Type SystemCommon Type System
• Conversion between each type:Conversion between each type:
UnBoxing ConversionUnBoxing Conversion
Convert Reference Type to Value TypeConvert Reference Type to Value Type
int i = (int) o;int i = (int) o;
16. Common Language SpecificationCommon Language Specification
• Microsoft’s CLS describes minimum setMicrosoft’s CLS describes minimum set
of features that a CLR-compliantof features that a CLR-compliant
compiler must supportcompiler must support
• Note: the CLR supports more featuresNote: the CLR supports more features
than the CLS describesthan the CLS describes
– Using these features prevents inter-Using these features prevents inter-
language operabilitylanguage operability
17. .NET Framework and CLR.NET Framework and CLR
Garbage CollectionGarbage Collection
Garbage collection is the process ofGarbage collection is the process of
automatically freeing up memory when anautomatically freeing up memory when an
object it been allocated to is no longerobject it been allocated to is no longer
being usedbeing used
18. .NET Framework and CLR.NET Framework and CLR
Benefits of Garbage CollectionBenefits of Garbage Collection
Garbage collection prevents the followingGarbage collection prevents the following
errors:errors:
Forgetting to destroy objectsForgetting to destroy objects
Attempting to destroy the same object moreAttempting to destroy the same object more
than oncethan once
Destroying an active objectDestroying an active object
19. myAssembly.DLLmyAssembly.DLL
.NET Framework and CLR.NET Framework and CLR
AssembliesAssemblies
myAssembly.DLLmyAssembly.DLL
Single ModuleSingle Module Multiple ModulesMultiple Modules
ManifestManifestManifestManifest
MetadataMetadataMetadataMetadata
IL CodeIL CodeIL CodeIL Code
Util.netmoduleUtil.netmodule
MetadataMetadataMetadataMetadata
IL CodeIL CodeIL CodeIL Code
Graphic.BMPGraphic.BMP
ResourcesResourcesResourcesResources
MetadataMetadataMetadataMetadata
IL codeIL codeIL codeIL code
ResourcesResourcesResourcesResources
ManifestManifestManifestManifest
20. .NET Framework and CLR.NET Framework and CLR
AssembliesAssemblies
• Advantages of Assemblies:Advantages of Assemblies:
– Self-DescribingSelf-Describing
– Side by Side executionSide by Side execution
– Ease of Deployment (avoid DLL-Hell)Ease of Deployment (avoid DLL-Hell)
– Ease of uninstallationEase of uninstallation
21. .NET Framework and CLR.NET Framework and CLR
AssembliesAssemblies
• Structure of an Assembly:Structure of an Assembly:
– ManifestManifest
– Type MetaDataType MetaData
– MSIL CodeMSIL Code
– Resources (optional)Resources (optional)
22. .NET Framework and CLR.NET Framework and CLR
ManifestManifest
• Data Structures stores details ofData Structures stores details of
an Assembly:an Assembly:
– Assembly Name and versionAssembly Name and version
– OS and Processor used to built toOS and Processor used to built to
– List of Dependencies filesList of Dependencies files
– Strong Name InformationStrong Name Information
23. .NET Framework and CLR.NET Framework and CLR
MetadataMetadata
• Type InformationType Information
– More complete than IDL / TLBMore complete than IDL / TLB
– Automatically bound into assemblyAutomatically bound into assembly
• InseparableInseparable
• Stored in binary formatStored in binary format
– Describes every class typeDescribes every class type
– Used by VS.NET IntelliSenseUsed by VS.NET IntelliSense™™
, compilers,, compilers,
runtime, etc.runtime, etc.
24. .NET Framework and CLR.NET Framework and CLR
AssembliesAssemblies
• Two kind of Assemblies:Two kind of Assemblies:
– Static AssembliesStatic Assemblies
• Persisted in diskPersisted in disk
• Most usedMost used
– Dynamic AssembliesDynamic Assemblies
• Build on the fly using Reflection APIBuild on the fly using Reflection API
• Exists in MemoryExists in Memory
• Can be converted to Static AssembliesCan be converted to Static Assemblies
• Less usedLess used
25. .NET Framework and CLR.NET Framework and CLR
AssembliesAssemblies
• Types of Static AssembliesTypes of Static Assemblies
– Single File AssembliesSingle File Assemblies
Using only one file to store all parts of anUsing only one file to store all parts of an
Assembly (Manifest, Metadata, IL, Res)Assembly (Manifest, Metadata, IL, Res)
– Multi File AssembliesMulti File Assemblies
Implementation of an Assembly split overImplementation of an Assembly split over
several files. Every part called .NET module.several files. Every part called .NET module.
26. • Using One or more assembliesUsing One or more assemblies
• Assemblies resolutionAssemblies resolution
– Using metadataUsing metadata
• Local (preferred)Local (preferred)
• Assembly Global CacheAssembly Global Cache
• Resolution uses version number, too!Resolution uses version number, too!
• Different applications may use differentDifferent applications may use different
versions of an assemblyversions of an assembly
– Easier software updatesEasier software updates
– Easier software removalEasier software removal
.NET Framework and CLR.NET Framework and CLR
CLR ApplicationsCLR Applications
27. .NET Framework and CLR.NET Framework and CLR
Shared AssembliesShared Assemblies
• Machine-level AssemblyMachine-level Assembly
• Stored in Global Assembly CacheStored in Global Assembly Cache
• It has Unique Identity called Strong NamesIt has Unique Identity called Strong Names
which consists of Public Key Tokenwhich consists of Public Key Token
28. .NET Framework and CLR.NET Framework and CLR
Side By Side ExecutionSide By Side Execution
• No more break compatibility problemsNo more break compatibility problems
• Having more than one version of anHaving more than one version of an
AssemblyAssembly
• Each application can use its own version ofEach application can use its own version of
an Assemblyan Assembly
• Versioning Number format:Versioning Number format:
<major>.<minor>.<build>.<revision><major>.<minor>.<build>.<revision>
29. Executing Managed IL CodeExecuting Managed IL Code
• When loaded, the runtime creates method stubsWhen loaded, the runtime creates method stubs
• When a method is called, the stub jumps toWhen a method is called, the stub jumps to
runtimeruntime
• Runtime loads IL and compiles itRuntime loads IL and compiles it
– IL is compiled into native CPU codeIL is compiled into native CPU code
• Method stub is removed and points to compiledMethod stub is removed and points to compiled
codecode
• Compiled code is executedCompiled code is executed
• In future, when method is called, it just runsIn future, when method is called, it just runs
32. .NET Framework and CLR.NET Framework and CLR
Application DomainApplication Domain
• Process Isolation:Process Isolation:
• In Win32 OS Every Application processIn Win32 OS Every Application process
isolated from each otherisolated from each other
• Memory Address is process relative whichMemory Address is process relative which
means address of memory from onemeans address of memory from one
application process is useless/not availableapplication process is useless/not available
for other application processfor other application process
33. .NET Framework and CLR.NET Framework and CLR
Application DomainApplication Domain
• Application Domain provides such anApplication Domain provides such an
isolation for every managed applicationisolation for every managed application
which targeted .NET CLRwhich targeted .NET CLR
• Much better than Win32 Process Isolation.Much better than Win32 Process Isolation.
Can have multiple domain within oneCan have multiple domain within one
processprocess
34. Just in Time(JIT) CompilersJust in Time(JIT) Compilers
• Standard JITStandard JIT
– The default JITThe default JIT
– Operates a bit more slowly but performs aOperates a bit more slowly but performs a
high level of optimization.high level of optimization.
• EconoJITEconoJIT
– Very fast compilation, but produces un-Very fast compilation, but produces un-
optimized code.optimized code.
• PreJITPreJIT
– The invocation of the Standard JIT at theThe invocation of the Standard JIT at the
time that an application is installed.time that an application is installed.
35. C#C#
• A new language designed expressly for the .NETA new language designed expressly for the .NET
FrameworkFramework
– Syntax based on C/C++Syntax based on C/C++
• Built on the CLR, withBuilt on the CLR, with
– Support for the CTS:Support for the CTS:
• ClassesClasses
• InheritanceInheritance
• Method overloadingMethod overloading
• Much moreMuch more
• Has only a couple of small things that aren’t inHas only a couple of small things that aren’t in
VB.NETVB.NET
• Co-authored by Anders Hejlsberg and ScottCo-authored by Anders Hejlsberg and Scott
Wiltamuth.Wiltamuth.
36. What is C#?What is C#?
"C# is a simple, modern, object oriented,"C# is a simple, modern, object oriented,
and type-safe programming languageand type-safe programming language
derived from C and C++. C# (pronouncedderived from C and C++. C# (pronounced
'C sharp') is firmly planted in the C and C+'C sharp') is firmly planted in the C and C+
+ family tree of languages, and will+ family tree of languages, and will
immediately be familiar to C and C++immediately be familiar to C and C++
programmers. C# aims to combine theprogrammers. C# aims to combine the
high productivity of Visual Basic and thehigh productivity of Visual Basic and the
raw power of C++."raw power of C++."
37. The Development of C#The Development of C#
• C and UNIXC and UNIX
• C++ Modernizes CC++ Modernizes C
• C at MicrosoftC at Microsoft
• C++ at MicrosoftC++ at Microsoft
• Visual Basic’s SimplicityVisual Basic’s Simplicity
• Sun Creates JavaSun Creates Java
• Microsoft .NET and C#Microsoft .NET and C#
38. C#C#
C++C++
Feature richnessFeature richness
Direct access to memoryDirect access to memory
Legacy keywordsLegacy keywords
JavaJava
Class structureClass structure
Single inheritanceSingle inheritance
InterfacesInterfaces
Garbage CollectionGarbage Collection
Code safetyCode safety
ReflectionReflection
Convenience &Convenience &
Additional FeaturesAdditional Features
PropertiesProperties
IndexesIndexes
AttributesAttributes
DelegatesDelegates
39. ClassClass
• Classes serve as templates for creating objectsClasses serve as templates for creating objects
• Example:Example:
public class Personpublic class Person
{{
private string name;private string name;
private int age;private int age;
public void SetAge(int newAge)public void SetAge(int newAge)
{{
age = newAge;age = newAge;
}}
}}
40. Access ModifierAccess Modifier
• Accessibility level can be set to:Accessibility level can be set to:
– publicpublic
– privateprivate
– protectedprotected
– internalinternal
– internal protectedinternal protected
41. InheritanceInheritance
• Inheritance enables creation of a class that's just likeInheritance enables creation of a class that's just like
some existing class with a few minor specializationssome existing class with a few minor specializations
public class Shape {public class Shape {
//code for the base class//code for the base class
}}
public class Rectangle : Shape {public class Rectangle : Shape {
//code for the shape rectangle//code for the shape rectangle
}}
42. FieldField
Properties are attributes associated with objectsProperties are attributes associated with objects
public class Button: Controlpublic class Button: Control
{{
private string text;private string text;
public string Text {public string Text {
get {get {
return text;return text;
}}
set {set {
text = value;text = value;
Repaint();Repaint();
}}
}}
}}
Button b = new Button();Button b = new Button();
b.Text = "OK";b.Text = "OK";
string s = b.Text;string s = b.Text;
43. Static vs. InstanceStatic vs. Instance
FieldsFields
MethodsMethods
Static/SharedStatic/Shared
Only one copyOnly one copy
of the fieldof the field
existsexists
Cannot accessCannot access
any instance dataany instance data
in the classin the class
InstanceInstance
Default, each object ofDefault, each object of
that class has its ownthat class has its own
copycopy
Implicitly receives aImplicitly receives a
reference to the objectreference to the object
on which it's workingon which it's working
44. Static vs. Instance (Example)Static vs. Instance (Example)
class Test {class Test {
int x;int x;
static int y;static int y;
void InstanceF() {void InstanceF() {
x = 1; // Ok, same as this.x = 1x = 1; // Ok, same as this.x = 1
y = 1; // Ok, same as Test.y = 1y = 1; // Ok, same as Test.y = 1
}}
static void StaticF() {static void StaticF() {
x = 1; // Error, cannot access this.xx = 1; // Error, cannot access this.x
y = 1; // Ok, same as Test.y = 1y = 1; // Ok, same as Test.y = 1
}}
static void Main() {static void Main() {
Test t = new Test();Test t = new Test();
t.x = 1; // Okt.x = 1; // Ok
t.y = 1; // Error, cannot access static member throught.y = 1; // Error, cannot access static member through
// instance// instance
Test.x = 1; // Error, cannot access instance member throughTest.x = 1; // Error, cannot access instance member through
// type// type
Test.y = 1; // OkTest.y = 1; // Ok
}}
}}
45. IndexerIndexer
• Indexers are members that enables anIndexers are members that enables an
object to be indexed in the same way asobject to be indexed in the same way as
an arrayan array
46. Indexer (Example)Indexer (Example)
class IndexerClass {class IndexerClass {
private int[] myArray = new int[100];private int[] myArray = new int[100];
public int this[int index] // indexer declarationpublic int this[int index] // indexer declaration
{{
get { /* code for the get accessor */ }get { /* code for the get accessor */ }
set { /* code for the get accessor */ }set { /* code for the get accessor */ }
}}
}}
public class MainClass {public class MainClass {
public static void Main() {public static void Main() {
IndexerClass b = new IndexerClass();IndexerClass b = new IndexerClass();
b[3] = 256;b[3] = 256;
b[5] = 1024;b[5] = 1024;
for (int i=0; i<=10; i++)for (int i=0; i<=10; i++)
Console.WriteLine("Element #{0} = {1}", i, b[i]);Console.WriteLine("Element #{0} = {1}", i, b[i]);
}}
}}
47. DelegateDelegate
• Delegates are objects that contain aDelegates are objects that contain a
reference to a methodreference to a method
– If the method is an instance method to aIf the method is an instance method to a
particular objectparticular object
• Delegate type contains a signatureDelegate type contains a signature
– Which must match method to be calledWhich must match method to be called
48. Delegate (Example)Delegate (Example)
// delegate declaration// delegate declaration
delegate void SimpleDelegate();delegate void SimpleDelegate();
// delegate instantiation and invocation// delegate instantiation and invocation
class Test {class Test {
static void F() {static void F() {
System.Console.WriteLine("Test.F");System.Console.WriteLine("Test.F");
}}
static void Main() {static void Main() {
SimpleDelegate d = new SimpleDelegate(F);SimpleDelegate d = new SimpleDelegate(F);
d();d();
}}
}}
49. EventEvent
public delegate void EventHandler(public delegate void EventHandler(
object sender, EventArgs e);object sender, EventArgs e);
public class Button: Controlpublic class Button: Control
{{
public event EventHandler Click;public event EventHandler Click;
protected void OnClick(EventArgs e) {protected void OnClick(EventArgs e) {
if (Click != null) Click(this, e);if (Click != null) Click(this, e);
}}
}}
void Initialize() {void Initialize() {
Button b = new Button(...);Button b = new Button(...);
b.Click += new EventHandler(ButtonClick);b.Click += new EventHandler(ButtonClick);
}}
void ButtonClick(object sender, EventArgs e) {void ButtonClick(object sender, EventArgs e) {
MessageBox.Show("You pressed the button");MessageBox.Show("You pressed the button");
}}
50. AttributeAttribute
• How do you associate information withHow do you associate information with
types and members?types and members?
– Category of a propertyCategory of a property
– Transaction context for a methodTransaction context for a method
– XML persistence mappingXML persistence mapping
• Traditional solutionsTraditional solutions
– Add keywords or pragmas to languageAdd keywords or pragmas to language
– Use external files (e.g., .IDL, .DEF)Use external files (e.g., .IDL, .DEF)
• C# solution: AttributesC# solution: Attributes