Sunteți pe pagina 1din 58

C# Programming and

.NET Concepts
Books for Reference
C# and the .NET Platform (2 Ed)
By Andrew Troelsen
Dreamtech Publications
Microsoft Visual C# .NET
By Mickey Williams
Microsoft Press

2
Chapter - 1

The Philosophy of .NET

3
Objectives
Understanding the previous state of
affairs
The .NET Solution
Building blocks of .NET Platform
CLR, CTS, and CLS
.NET Base Class Libraries

4
Understanding the
previous state of affairs
As a C/Win32 API Programmer
It is complex
C is a short/abrupt language
Manual memory management, ugly pointer
arithmetic, ugly syntactic constructs
Not a OO language
As a C++/MFC Programmer
Root is C
C++ with MFC is still complex and error-prone
As a VB 6 Programmer
Not a complete OOP (Object-aware) Why?
Doesnt support inheritance
No multithreading
No parameterized Classes
Low-level API calls are complex
5
Previous state of affairs
As a Java/J2EE Programmer
Use of Java front-to-back during development
cycle
No language freedom!
Pure Java is not suitable for graphic intensive
problems (E.g. 3D game)
No cross-language integration
As a COM Programmer
Complex creation of COM types
Active Template Library (ATL)
Forced to contend with brittle/fragile registration
entries
Deployment issues
6
.NET Solution
Full interoperability with existing Win32 Code
Existing COM binaries can interoperate with .NET binaries
Complete and total language integration
Supports cross-language inheritance, exception handling, and
debugging
Common runtime engine shared by all .NET aware
languages
A base class library
Good object model used by all .NET aware languages
No more COM plumbing!
No IClassFactory, IUnKnown, IDispatch, etc.
Truly simplified deployment model
No need to register a binary unit into the system registry
Allows multiple versions of same *.dll

7
.NET Framework
VB C++ C# JScript J#

Common Language Specification

Visual Studio.NET
ASP.NET Windows
Web Forms Web Services Forms

ADO.NET and XML

Base Class Library

Common Language Runtime

Operating System

8
Building Blocks of .NET
CLR (Common Language Runtime)
To locate, load, and manage .NET types
Automatic memory management, language
integration, and type safety
CTS (Common Type System)
Describes all possible data types and
programming constructs supported by the
runtime
CLS (Common Language Specification)
A set of rules that defines a subset of types and
specifications

9
CLR (Common Language Runtime)
CLR sits on top of OS (same as JVM of Java)
CLR loads modules containing executables and executes
them
Code may be managed or unmanaged
Managed code consists of instructions in pseudo random
code called CIL (Common Intermediate Language). CIL
instructions are JIT compiled into native machine code at
runtime
JIT compiled methods reside in cache until the applications
life time
Advantages of managed code: type safety, memory
management, and code verification security
CLR can translate code from C#, J#, C, C++, VB, and
Jscript into CIL.
CLR doesnt launch a new process for every application. It
launches one process and hosts individual applications in
application domains
10
Base Class Libraries
Encapsulates various primitives like: threads, file
IO, graphical rendering, and other interaction with
HW devices
It also provides: database manipulation, XML
integration, Web-enabled front-end.

Data Access GUI Base Class Libraries

Threading File IO XML/SOAP

Common Language Runtime

CTS CLS
11
C#
Almost same as Java
No pointers required
Automatic memory management (No delete)
Enumeration, class, structure, etc.
Operator overloading allowed
Interface-based programming techniques
Assign characteristics to types (same as COM
IDL)
C# can produce code that can run only on .NET
environment (unlike COM server or Win32 API)
12
Understanding Assemblies
Windows applications have dependencies
on one or more DLLs
These DLLs may contain COM classes
registered in System registry
When these components are updated,
applications may break 'DLL hell'
Solution: .NET Assemblies
C# .NET compiler doesn't generate
machine code.
It is compiled into "assembly"

13
Understanding Assemblies
An assembly is a logical collection of one or
more EXE or DLL files containing an
application code & resources
.NET binaries not described using com
libraries & not registered into system
registry
.NET binaries contain platform agnostic
intermediate language (IL) & type metada

14
Assembly
Metadata

IL
C# source code + C# .NET Compiler =
Assembly

Intermediate Language (IL/CIL):


Same as first pass of compiler. It can't be executed (it is not
in binary format)
Metadata
Describes the assembly contents [characteristics]
No need for component registry
Each assembly includes information about references to other
assemblies
E.g. If you have a class called Car in a given assembly, the
type metadata describes Car's base class, which interfaces
are implemented by Car, description of members of Car.
It is always present & is automatically generated by a
given .NET aware compiler
15
Assembly
When CLR loads your application, it examines your
program's metadata to know which external
assemblies are required for execution
Private assemblies
Used by single application
Is not shared
Most preferred method
Shared assemblies
Intended for multiple applications
Manifest
Assemblies themselves are described using metadata
manifest
The metadata of assemblies: version, list of
externally defined assemblies, etc.

16
Single-file & Multi-file Assembly
Single-file assemblies
Assemble composed of a single *.dll or *.exe module
It contains necessary CIL, metadata & manifest in a
autonomous, single, well defined package
Disadvantage -The end user may end up downloading
a large blocks of data that is not really needed
Multi-file assemblies
Composed of numerous ,NET binaries, each of which
termed as module
When building one module (i.e. primary module)
contains assembly manifest, CIL & metadata
Necessity when partition an assemble into discrete
modules, end up with a more flexible deployment
option.
17
The Role of CIL
CIL Common Intermediate Language
It is a language that sits on any platform
specific instruction set
Which .NET aware language select
compiler emits that CIL instructions
Eg: C# code models a calculator

18
Example of CIL
CIL sits above a specific compiler public class Calc
(C#, J#, etc.) {
The associated compiler emits CIL public int Add(int x, int y)
instructions { return x + y; }
}
using System;
}
namespace Calculator
{

public class CalcApp


{
All .NET aware languages
emit same CIL instructions
public static void Main(string[] args)
{
Calc c = new Calc();
int ans = c.Add(10, 84);
Console.WriteLine(ans);
Console.ReadLine();
}
}

19
CIL of Add() Method
.method public hidebysig instance int32 Add(int32 x,
int32 y) cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init ([0] int32 CS$00000003$00000000)
IL_0000: ldarg.1
IL_0001: ldarg.2
IL_0002: add
IL_0003: stloc.0
IL_0004: br.s IL_0006
IL_0006: ldloc.0
IL_0007: ret
} // end of method Calc::Add

20
The Benefits of CIL
Language integration .NET aware
languages produce identical CIL
instructions. So all are able to interact
with a well defined binary form.
CIL is platform agnostic
.NET allows build application with
language choice

21
Compile CIL to Platform-
Specific Instructions
Entity that compile CIL code into CPU
instructions is called JIT (Just-In-Time)
Jitter
the jitter is well equipped for low
memory environment as well as high
memory environment

22
CIL to Execution
Desktop

CIL JIT Server

Pocket PC

Jitter compiles CIL instructions on the fly into


corresponding machine code and cache it. This is
useful for not recompiling, if the same method is
called again. Eg: Print()

23
The role of .NET type Metadata
.NET assembly contains full, complete &
accurate metadata, which describes each
& every type (class, structure,
enumeration etc.) defined in the binary,
as well as the members of each type
( properties, methods, events etc)
Eg. Metadata for Add() method
TypeDef #2 (02000003)
TypeDefName: calculatorExample.Cals
MethodName: Add( 06000003)
Flags:
RVA: 0x00002090
Implflags: [IL] [managed] (000000)
Return Type: I4

24
The role of .NET type Metadata
Metadata is used by various object
browsing utilities, debugging tools & the
c# compiler itself
It is a backbone of numerous .NET
technologies including remoting,
reflection, late binding, XML services, &
object serialization

25
The role of Assembly Manifest
Metadata that describe itself
Manifest documents all external
assemblies required by the current
assembly to function correctly, the
assembly version, copyright info. Etc
Eg: Csharpcalculator. Exe manifest

26
External
Manifest Assembly

.assembly extern mscorlib


{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 1:0:5000:0
}
.assembly ConsoleApplication1
{

.hash algorithm 0x00008004


.ver 1:0:2058:39833
}
.module ConsoleApplication1.exe
// MVID: {51BE4F31-CBD0-4AE6-BC9D-F9A4976795FD}
.imagebase 0x00400000
.subsystem 0x00000003
.file alignment 4096
.corflags 0x00000001
// Image base: 0x070b0000

27
Common Type System (CTS)
CTS is a formal specification that
describes how a given type must be
defined for CLR
CTS Class Type
CTS Structure Type
CTS Interface Type
CTS Enumeration type
CTS Delegate type
28
CTS Class Type
Same as C++ class
Can contain members: methods,
properties, events, etc.
Support for abstract members that
define a polymorphic interface for
derived classes
Multiple inheritance is not allowed

29
CTS Class Type
In c# classes are declared using class
keyword
// A c# class calc
{
public int Add( int x, int y)
{
return x+y;
}
}
30
CTS Class Characteristics
"sealed"? sealed classes can't function as
base classes
Implement any interfaces? An interface
is a collection of abstract members
Abstract or Concrete? Abstract classes
(to define common behaviors for derived)
can't be created directly but concrete
classes can.
Visibility? visibility attribute to know
whether external assemblies can use it.

31
CTS Structure types
Same as C/C++
Derived from a common base class System.ValueType
Structures are suited for modeling geometric &
mathematical data.
C# use struct keyword
struct Point
{// structures can contain fields
public int xpos, ypos;
// structures can contain parameterized constructors
public point (int x, int y)
{ xpos = x; ypos = y;}
// structure may define methods
public void Display()
{
console. WriteLine(({0},{1}, xpos, ypos);
}
}
CTS Interface Type
Same as pure abstract class of C++
These are collection of abstract member
definitions, which are supported by given class or
structure
.NET interfaces do not derive a common base
interface.
C# use interface keyword
CTS permits a given interface derive from multiple
base interfaces
public interface IDraw
{
void Draw();
}
33
CTS Enumeration type

To group name/value pairs under a specific name


Default Storage: System.Int32 (could be changed)
CTS demands that enumerated types derive from a
common base class, System.Enum
C# use enum keyword
Public enum character type
{ wizard = 100, fighter = 300, thief = 200 }

CTS Delegate type


Same as C's function pointer, but derive from
System.MulticastDelegate
Useful for event handling (ASP .NET)
Support for multicasting & asynchronous method invocation
C# use delegate keyword

34
CTS type members

A type member constrained by the set


{constructor, finalizer, operator etc.}
CTS defines adornments (i. e. visibility traits
public, private etc.)
Member may be declared as abstract for
polymorphic behavior on derived types
Also configured as ststic or instance entities

Intrinsic CTS Data Types


CTS have well defined intrinsic data types
Types define in mscorlib.lib
35
Intrinsic CTS Data Types
.NET Base Type C# Type
System.Byte Byte
System.SByte sbyte
System.Int16 short
System.Int32 int
System.Int64 long
System.UInt64 ulong
System.Single float
System.Double double
System.Object object
System.String string
System.Boolean bool
36
Common Language Specification
(CLS)
Set of guidelines that describe the minimal
and complete set of features a given .NET
aware compiler must support
C# uses + for concatenation whereas VB
.NET uses &
C# allows operator overloading but VB .NET
does not!
The void functions may differ in syntax:
' VB .NET // C#
Public Sub Foo() public void Foo()
'. { . }
End Sub
37
Common Language Specification
(CLS)
CLS must support to produce code
that can be hosted by CLR
The rules serve as a guide to third-
party compiler designers & library
builders
CLS is the subset of CLT

38
CLS Compliance
C# Type CLS Compliance
byte Yes
sbyte No
short Yes
int Yes
long Yes
ulong No
float Yes
double Yes
object Yes
string Yes
char Yes
bool Yes 39
Example
public class Calc
{
// CLS compliant
public int Add(int x, int y)
{ return x + y; }

// Not CLS compliant


public ulong Add(ulong x, ulong y)
{ return x + y; }
}
Once a method is CLS compliant, then all the
.NET aware languages can interact with that
implementation

40
Common Language Runtime
(CLR)
CLR is the heart & soul of the .NET
framework
CLR is a runtime environment - c# &
other .net languages are executed
Supports cross language interoperability
The fig shows major components of CLR
CLR
CTS
IL
Execution support function
garbage collection
class loader
memory layout

41
Common Language Runtime
(CLR)
CLR services-
Loading & execution of programs
Memory isolation for applications
Verification of type safety
Compilation of IL into native executable code
Providing metadata
Memory mngt. (automatic garbage collection)
Enforcement of security
Interoperability with other language
Managing exceptions & errors
Support for tasks debugging & profiling

42
CLR .NET .NET Compiler
Source
Code
DLL or EXE
(CIL)

mscoree.dll

Class Loader

Base Class
Libraries Jitter
(mscorlib.dll)

Platform
Specific code

mscoree.dll
Execute
MicroSoft Common
Object Runtime Execution Engine .NET Execution Engine
.NET Namespace
MFC, Java, VB 6.0 have predefined set of
classes; C# doesn't
To keep all types within the base class
libraries, .NET platform use namespace
concept eg. System.IO
Any language targeting the .NET runtime
makes use of the same namespaces and
same types as C#
System is the root namespace
using directive used to import namespaces
44
Example in C# System Namespace

using System;
public Class MyApp
{
public static void Main() System
Console class in
Namespace
{
Console.WriteLine("Hello World");
}
}

45
Example in VB .NET
Imports System
Public Module MyApp
Sub Main()
Console.WriteLine("Hello World")
End Sub
End Module

46
Example in Managed C++
#using <mscorlib.dll>
using namespace System;
void Main()
{
Console::WriteLine("Hello World");
}
all programs use console class defined in
the system namspace- beyond the syntatic
variations applications look alike, both
physically & logically

47
Sample .NET namespaces
System primitive types, garbage
collection, etc
System.Collections Container objects: ArrayList,
Queue, etc.
System.Data For Database manipulations
System.Data.Common ADO .NET
System.Data.OleDb
System.Data.SqlClient
System.IO file IO, buffering, etc.
System.Drawing GDI+ primitives, bitmaps, fonts,
System.Drawing.2D icons, etc.

System.Threading Threads

48
Accessing the Namespace
In c# - use keyword using
Eg: using System;
using System.Drawing;
using Syatem.Windows.Forms;
Once specified namespaces, they are
free to create instances of the types
they contain

49
Eg: create an instance of
bitmaap class
// explicitly list the namespaces
using System;
Using syatem.Drawing()
Class Myapp()
{
pubplic void Display logo()
{
Bitmap Companylogo = new bitmap(20.20);
..
}
}

50
// Not listing System.Drawing namespace
using System;

Class Myapp()
{
pubplic void Display logo()
{ // use fully qualified name
Syatem.Drawing.Bitmap Companylogo = new
Syatem.Drawing.bitmap(20.20);
..
}
}
using helps to create short hand notation for specifying a
types fully qualified name

51
using helps to create short hand
notation for specifying a types fully
qualified name
Referencing external assemblies
Majority of the .NET framework
assemblies are located under specific
directory called Global Assembly Cache
(GAL)
On windows machine, this can be located
under %windir%\Assembly

52
Using ildasm.exe
Intermediate Language Disassembler
utility
It allows to load up any .NET
assembly & investigate its contents,
including associated manifest, CIL &
type metadata
ildasm.exe installed under c:\program
files\ microsoft visual studio8\
SDK\v2.0\bin

53
Using ildasm.exe
Viewing CIL code double click the
main() method of perticular
application class
Viewing type metadata press ctrl+M
to view currently loaded assembly
Viewing assembly metadata double
click on MANIFEST icon

54
Deplyoing the .NET runtime
.NET assemblies can be executed only
on a m/c that has the .NET
framework installed
Available frame work - .NET frame
work 2.0 SDK, Visual studio 2005
Setup package dotnetfx.exe (then it
contain .NET base class libraries, .NET
runtime & .NET infrastructures [ such
as GAC])

55
Questions
What is .net Framework? With a neat diagram
explain the building blocks of .net platform?
Explain with neat diagram the workflow that takes
place b/w your source code, .net execution engine?
What are the key features of c#?
Write short notes on CIL & Assembly manifest
What is CLR? What are the features of CLR
What is CTS? List out some Intrinsic CTS
datatypes?
Explain the functions of .NET runtime (CLR)
Explain about .net namespaces?

56
Questions
Write short notes on: .net binaries & .net
type metadata
Explain briefly about ILDASM?
Briefly discuss the state of affairs that
eventually led to the .NET platform. What is
the .NET solution and what C# brings to
the table.
Write the difference b/w single-file &
multifile assemblies.
What are namespaces? List and explain the
purpose of at least five namespaces.

57
End of Chapter 1

58

S-ar putea să vă placă și