You are on page 1of 61

Title: Course Code:

C# Programming and .Net 10CS761

Hrs/Week: 04 Core/Elective: Elective

Type of Course: Lecture + Total Contact Hours: 52 Hrs


Demonstration
IA. Marks :25 U. Exam Marks:100

Faculty John Prakash Veigas


Course Outcomes
C406.1 Assess the shortcomings in previous technologies and to get
insight .NET framework and its runtime environment

C406.2 To discuss the C# language fundamentals, Object Oriented


Concepts and C# class hierarchy that supported by .net framework

C406.3 To Design, develop and build applications in C# using .NET


centric building blocks
C406.4 To discuss new features that are unique to c# such as properties,
indexers, delegates, events, assembly and namespaces

2/1/2018 C# and .Net 2


Text Books:
1. Andrew Troelsen: Pro C# with .NET 3.0, 4th Edition,
Wiley India, 2009. Chapters: 1 to 11 (up to pp.369)
2. E. Balagurusamy: Programming in C#, 2nd Edition,
Tata McGraw Hill, 2008.
(Programming Examples 3.7, 3.10, 5.5, 6.1, 7.2, 7.4, 7.5, 7.6, 8.1,
8.2, 8.3, 8.5, 8.7, 8.8, 9.1, 9.2, 9.3, 9.4, 10.2, 10.4, 11.2, 11.4, 12.1,
12.4, 12.5, 12.6, 13.1, 13.2, 13.3, 13.6, 14.1, 14.2, 14.4, 15.2, 15.3,
16.1, 16.2, 16.3, 18.3, 18.5.18.6)
Reference Books:
1. Tom Archer: Inside C#, WP Publishers, 2001.
2. Herbert Schildt: C# The Complete Reference, Tata
McGraw Hill,2004.

2/1/2018 C# and .Net 3


Syllabus
 Understanding the Previous State of Affairs,
 The .NET Solution,
1 hr
 The Building Block of the .NET Platform (CLR,CTS,
and CLS),
 The Role of the .NET Base Class Libraries,
 What C# Brings to the Table
1 hr
 An Overview of .NET Binaries ( aka Assemblies ),
 the Role of the Common Intermediate Language,
 The Role of .NET Type Metadata,
1 hr
 The Role of the Assembly Manifast

2/1/2018 C# and .Net 5


Syllabus( Contd…)
 Compiling CIL to Platform –Specific Instructions, 1 hr
 Understanding the Common Type System
 Intrinsic CTS Data Types
 Understanding the Common Languages 1 hr
Specification
 Understanding the Common Language Runtime
 A tour of the .NET Namespaces
 Increasing Your Namespace Nomenclature, 1 hr
Deploying the .NET Runtime.

2/1/2018 C# and .Net 6


Understanding the Previous State of Affairs
Before discussing the benefits provided by C# and the .NET
platform, let us see history and understand the limitations of
the previous state of affairs
Life As a C/Win32 API Programmer
 Developing software for the Windows family of operating systems
using the C programming language and Windows API
 Numerous applications have been successfully created
Limitations:
 C is a very terse language
 Developers forced to contend with memory management, ugly
pointer arithmetic, ugly syntactical constructs
 It lacks the benefits provided by the object-oriented approach
 Combining thousands of global functions and data types defined by
the Win32 API  buggy applications
2/1/2018 C# and .Net 7
Life As a C++/MFC Programmer

 An object-oriented layer on top of C


 C++ programmers benefit from the “pillars of OOP”
 Microsoft Foundation Classes (MFC) provides the developer
with a set of C++ classes that facilitate the construction of
Win32 applications
 MFC wraps the raw Win32 API behind a number of classes,
magic macros, and numerous code-generation tools(wizards)
 Roots are from C
 Painful aspects of the C language still remains

2/1/2018 C# and .Net 8


Life As a Visual Basic 6.0 Programmer
To enjoy a simpler lifestyle, many programmers shifted away from
the world of C++ based frameworks to kinder, gentler languages
such as Visual Basic 6.0 (VB6).
VB6 is popular due to its:
 ability to build complex user interfaces
 code libraries (e.g., COM servers)
 data access logic with minimal fuss
 VB6 hides the complexities of the raw Win32 API from view using
a number of integrated code wizards, intrinsic data types, classes
Major downfall of VB6
 It is not a fully object-oriented language; rather, it is “object
aware.”
 No classical inheritance ( no is-a relationship)
 No intrinsic support for parameterized class construction
 No support for multithreaded applications
2/1/2018 C# and .Net 9
Life As a Java/J2EE Programmer
 Completely object oriented
 Java is platform independent
 Provides programmers with a large number of predefined
“packages” that contain various type definition
 Supports database connectivity, messaging support, web-
enabled front ends, and a rich user interface.
Limitations
 Must use Java front-to-back during the development cycle
 Java offers little hope of language integration
 Pure Java is simply not appropriate for many graphically or
numerically intensive applications
 little support for true cross-language integration.
2/1/2018 C# and .Net 10
Life As a COM Programmer
Component Object Model is an architecture that says in effect,
“If you build your classes in accordance with the rules of COM, you end up
with a block of reusable binary code.”
 The beauty of a binary COM server is that it can be accessed in a
language-independent manner
C++ programmers can build COM classes that can be used by VB6
Delphi programmers can use COM classes built using C
and so on..
 Another benefit of COM is its location-transparent nature.
e.g.: Using constructs such as application identifiers (AppIDs), stubs,
proxies, and the COM runtime environment, programmers can avoid the
need to work with raw sockets, RPC calls, and other low-level details
Limitations
 COM’s language independence is somewhat limited
e.g. : COM has no support for classical inheritance (is-a)
to reuse COM class types use “has-a” relationship
 COM components must be registered on the client systems
 It is impossible to run more than one version on same client
machine DLL Hell
2/1/2018 C# and .Net 11
Life As a Windows DNA Programmer
 Microsoft has been adding more Internet-aware features
into its family of operating systems and products
 Building a web application using COM-based Windows
Distributed interNet Applications Architecture (DNA) is
very complex
 Windows DNA requires the use of numerous technologies
and languages (ASP, HTML, XML, JavaScript, VBScript, and
COM(+), as well as a data access API such as ADO)
 One problem is that many of these technologies are
completely unrelated from a syntactic point of view
 Each language and/or technology has its own type system

2/1/2018 C# and .Net 12


The .NET Solution
.NET Framework is a completely new model for building
systems on the Windows family of operating systems, as
well as on numerous non-Microsoft operating systems
such as Mac OS X and various Unix/Linux distributions

2/1/2018 C# and .Net 13


Core features provided by.NET
 Full interoperability with existing code
 PInvoke allows C based libraries
 Complete and total language integration
 .NET supports cross-language inheritance, cross-language
exception handling, and cross-language debugging
 A common runtime engine shared by all .NET-aware
languages
 A base class library
 No more COM plumbing
 A truly simplified deployment model
 .NET allows multiple versions of the same *.dll to exist in
harmony on a single machine.

2/1/2018 C# and .Net 14


Building Blocks of the .NET Platform:
(CLR, CTS, and CLS)

2/1/2018 C# and .Net 15


CLR- Common Language Runtime
 The runtime layer is referred to as the common
language runtime
 primary role of the CLR is to locate, load, and manage
.NET types
 Takes care of a number of low-level details such as
memory management and performing security checks,
thread management, Exception handling, garbage
collection
 The code runs under the CLR is called Managed Code

2/1/2018 C# and .Net 16


CTS -Common Type System
 Standard specification fully describes all possible data
types and programming constructs supported by the
runtime
 It specifies how these entities can interact with each
other, and details how they are represented in the .NET
metadata format
 It is intended to allow programs written in different
programming languages to easily share information

2/1/2018 C# and .Net 17


Common Language Specification (CLS)
 It is a related specification that defines a subset of
common types and programming constructs that all .NET
programming languages can agree on.
 CLS defines a set of rules and restrictions that every
language must follow which runs under .Net framework
 The languages which follow these set of rules said to be
CLS compliant
 you make use of a data type or programming construct
that is outside of the bounds of the CLS, you cannot
guarantee that every .NET programming language can
interact with your .NET code library.
2/1/2018 C# and .Net 18
2/1/2018 C# and .Net 19
Base Class Libraries
 It is available to all .Net programming languages
 Base class library encapsulate various primitives
 Threads, file input/output (I/O), graphical rendering
 Interaction with various external hardware devices
 It also provides support for a number of services
required by most real-world applications.
 Define types that facilitates DB access
 XML manipulations
 web and desktop enabled front ends

2/1/2018 C# and .Net 20


Features of C#(What C# Brings to the Table?)
 No pointers required
 Automatic memory management through garbage
collection. –no delete keyword
 Formal syntactic constructs for enumerations, structures,
and class properties.
 Ability to overload operators for a custom types without
any complexity
 Ability to build generic types and generic members
 Full support for interface-based programming techniques.
 Full support for aspect-oriented programming (AOP)
techniques via attributes.

2/1/2018 C# and .Net 21


.NET Assemblies(.Net Binaries)
An Assembly is a Collection of types and resources that are built
to work together and form a logical unit of functionality

All .NET-aware compilers emit IL instructions and metadata


IL(Intermediate Language)/CIL(Common Intermediate Language)
/MSIL(Microsoft Intermediate Language) are all describing the
same exact entity
2/1/2018 C# and .Net 22
If all .NET languages compile down to ‘managed code,’
why do we need more than one compiler?
 programmers are a very particular lot when it comes to
our choice of programming language
 all programming languages have their own sets of
strengths and weaknesses. Different languages have
superior support for
 mathematical processing
 financial calculations, logical calculations,
 interaction with mainframe computers

2/1/2018 C# and .Net 23


.NET Assemblies(.Net Binaries)
 .NET binaries take the same file extension as COM servers
and unmanaged Win32 binaries (*.dll or *.exe)
 They have absolutely no internal similarities.
 When a *.dll or *.exe has been created using a .NET-aware
compiler, the resulting module is bundled into an assembly.
 .NET binaries are not registered into the system registry
 NET binaries do not contain platform-specific instructions
 NET binaries contains platform-agnostic intermediate
language (IL) and type metadata

2/1/2018 C# and .Net 24


.NET Assemblies(Contd…)
 Assembly contains CIL code, which is conceptually
similar to Java byte code in that it is not compiled to
platform-specific instructions until absolutely
necessary
 Assemblies also contain metadata that describes the
different characteristics of every “type” living within
the binary
 Eg: SportsCar
 each members
 Base class
 interfaces

2/1/2018 C# and .Net 25


.NET Assemblies(Contd…)
 .NET metadata is always present and is automatically
generated by a given .NET-aware compiler
 Assemblies themselves are also described using
metadata, which is officially termed a manifest
 The manifest contains information
 about the current version of the assembly, culture
information (used for localizing string and image resources)
 a list of all externally referenced assemblies that are
required for proper execution

2/1/2018 C# and .Net 26


Single File and Multi file Assemblies

 Single-file assemblies contain all the necessary CIL,


metadata, and associated manifest in an autonomous,
single, well-defined package.
 In many cases, there is a simple one-to-one
correspondence between a .NET assembly and the
binary file (*.dll or *.exe).
 if an assembly is composed of a single *.dll or *.exe,
then its called as a single-file assembly.

2/1/2018 C# and .Net 27


Single File and Multi file Assemblies(Contd..)
Multi-file assemblies are composed of numerous .NET
binaries, each of which is termed a module.
When building a multi-file assembly, one of these
modules (termed the primary module) must contain
the assembly manifest (and possibly CIL instructions
and metadata for various types).
The other related modules contain a module-level
manifest, CIL, and type metadata.

2/1/2018 C# and .Net 28


Why create a multifile assembly?
 When we partition an assembly into discrete modules, we
will get a more flexible deployment option.
- user is referencing a remote assembly that needs to be
downloaded onto his or her machine
 Runtime will only download the required modules

2/1/2018 C# and .Net 29


Role of Common Intermediate Language (CIL)
CIL is a language that sits above any particular platform-
specific instruction set.
 Regardless of which .NET aware language you choose (C#,
VB, Eiffel .NET), the associated compiler emits the CIL
instructions.
 compile C# Source code file using the C# compiler
(csc.exe),single-file *.exe assembly
 compile vb source code file using the VB.NET compiler
(vbc.exe)single-file *.exe assembly
 Each .NET-aware compiler produces nearly identical
CIL instructions.
2/1/2018 C# and .Net 30
Compiling CIL to Platform-Specific Instructions
 The entity that compiles CIL code into meaningful
CPU instructions is termed a just-in-time (JIT)
compiler (Jitter)
 JIT compiler optimizes CPU instruction based on
the underlying platform.
 Handheld device low memory environment
 back-end server

2/1/2018 C# and .Net 31


Common Type System
 A given assembly may contain any number of distinct
“types.”
 Type refers to member from the set
{class, structure, interface, enumeration, delegate}

2/1/2018 C# and .Net 32


CTS Class Types
 A class may be composed of any number of members
 properties,
 Methods
 events
 data points (fields)

// A C# class type.
public class Calc
{
public int Add(int x, int y)
{ return x + y; }
}
2/1/2018 C# and .Net 33
CTS Class Characteristics
Class Characteristic Meaning in Life

Is the class “sealed” or Sealed classes cannot function as a


not? base class to other classes.
Does the class An interface is a collection of abstract
implement any members that provide a contract
interfaces? between the object and object user.
Is the class abstract or Abstract class Objects cannot be
concrete? directly created, but are intended to
define common behaviors for derived
types.
What is the “visibility” Each class must be configured with a
of this class? visibility attribute
2/1/2018 C# and .Net 34
CTS Structure Types
 structure is a user defined type having value-based
semantics
// A C# structure type.
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;}

// Structures may define methods.


public void Display()
{
Console.WriteLine(“x={0},y= {1}", xPos, yPos);
}
}
2/1/2018 C# and .Net 35
CTS Interface Types
 Interfaces are named collection of abstract member
definitions, which may be supported (i.e.,
implemented) by a given class or structure

// A C# interface type.
public interface IDraw
{
void Draw();
}
2/1/2018 C# and .Net 36
CTS Enumeration Types
 Enumerations are programming construct that allows
us to group name/value pairs

// A C# enumeration type.
public enum CharacterType
{
Wizard = 100,
Fighter = 200,
Thief = 300
}

• By default, the storage used to hold each item is a 32-bit integer


• CTS demands that enumerated types derive from a common
base class System.Enum
2/1/2018 C# and .Net 37
CTS Delegate Types
 Delegates are the .NET equivalent of a type-safe C-style
function pointer
 .NET delegate is a class that derives from
System.MulticastDelegate
 provide a way for one entity to forward a call to another entity
 delegates have intrinsic support for
 multicasting (i.e., forwarding a request to multiple recipients)
 Asynchronous method invocations.

// This C# delegate type can 'point to' any method


// returning an integer and taking two integers as input.
public delegate int BinaryOp(int x, int y);

2/1/2018 C# and .Net 38


CTS Type Members
•A type member is constrained by the set
 constructor  property
 finalizer  indexer
 static constructor  field
 nested type  read only field
 operator  constant
 method  event

• each member has a given visibility


• Some members may be declared as abstract/static
2/1/2018 C# and .Net 39
Intrinsic CTS Data Types
CTS Data Type VB .NET C# Managed Extensions for C++ Keyword
System.Byte Byte byte unsigned char
System.Sbyte Sbyte sbyte signed char
System.Int16 Short short short
System.Int32 Integer int int or long
System.Int64 Long long __int64
System.UInt16 UShort ushort unsigned short
System.UInt32 UInteger uint unsigned int or unsigned long
System.UInt64 ULong ulong unsigned __int64
System.Single Single float Float
System.Double Double double Double
System.Object Object object Object^
System.Char Char char wchar_t
System.String String string String^
System.Decimal Decimal decimal Decimal
System.Boolean Boolean bool Bool
defined in an assembly named mscorlib.dll
40
2/1/2018 C# and .Net
Workflow of Common Language Runtime

Mscorree.dll Microsoft
Common Object Runtime
Execution Engine.

41
2/1/2018 C# and .Net
Workflow of Common Language Runtime
• Runtime can be understood as a collection of external
services that are required to execute a given compiled unit of
code
• CLR is physically represented by a library named mscoree.dll
• When an assembly is referenced for use, mscoree.dll is loaded
automatically, which in turn loads the required assembly into
memory.
• The runtime engine is responsible for a number of tasks:
– It is the entity in charge of resolving the location of an assembly
– Finding the requested type within the binary by reading the contained
metadata.
• The CLR then lays out the type in memory, compiles the
associated CIL into platform specific instructions, performs
any necessary security checks, and then executes the code
42
2/1/2018 C# and .Net
.NET namespaces
• Namespace is a grouping of related types
contained in an assembly
• Namespaces can be used to organize code in
any way the programmer desires.
• A single assembly can contain any namespaces,
each of which can contain any number of types
– Mscorlib.dll
• Namespaces avoid naming conflicts between
identifiers.
43
2/1/2018 C# and .Net
Accessing namespace programmatically
•Using Keyword
// Explicitly list the namespaces used by this file.
using System;
using System.Drawing;
class MyApp
{ •Using fully qualified name
public void DisplayLogo() // Not listing System.Drawing namespace!
{ using System;
// Create a 20_20 pixel bitmap. class MyApp
{
Bitmap companyLogo = new Bitmap(20, 20);
public void DisplayLogo()
} {
} // Using fully qualified name.
System.Drawing.Bitmap companyLogo =
new System.Drawing.Bitmap(20, 20);..
}
}
44
2/1/2018 C# and .Net
.NET Namespace .NET Namespace Meaning in Life

System.IO These namespaces include file I/O, buffering etc


System.IO.Compression IO namespaces also include support compression and
System.IO.Ports port manipulation
System.Net Contains types related to network programming
(requests/responses, sockets, end points, and so on).
System.Reflection These namespaces define types that support runtime
System.Reflection.Emit type discovery as well as dynamic creation of types.
System.Security security-centric namespaces you find numerous types
dealing with permissions, cryptography, and so on.
System.Threading defines types used to build multithreaded
applications.
System.Web Development of .NET web applications
System.Windows.Forms types that facilitate the construction of traditional
desktop GUI applications.
45
2/1/2018 C# and .Net
The Role of the Common
Intermediate Language

46
2/1/2018 C# and .Net
.Net aware compiler Produces CIL instructions

47
2/1/2018 C# and .Net
48
2/1/2018 C# and .Net
49
2/1/2018 C# and .Net
The Role of .NET Type Metadata
• .NET assembly contains full, complete, and
accurate metadata, which describes each and
every type (class, structure, enumeration, and
so forth) defined in the binary, as well as the
members of each type (properties, methods,
events, and so on).

50
2/1/2018 C# and .Net
51
2/1/2018 C# and .Net
The Role of the Assembly Manifest
• the manifest documents all external
assemblies required by the current assembly
to function correctly, the assembly’s version
number, copyright information, and so forth.
• Like type metadata, it is always the job of the
compiler to generate the assembly’s manifest

52
2/1/2018 C# and .Net
53
2/1/2018 C# and .Net
54
2/1/2018 C# and .Net
55
2/1/2018 C# and .Net
Understanding the Common
Language Specification
• The Common Language Specification (CLS) is a set of
rules that describe in vivid detail the minimal and
complete set of features a given .NET-aware compiler
must support to produce code that can be hosted by
the CLR, while at the same time be accessed in a
uniform manner by all languages that target the .NET
platform
• The crème de la crème of the CLS is the mighty Rule 1:
• Rule 1: CLS rules apply only to those parts of a type
that are exposed outside the defining assembly.

56
2/1/2018 C# and .Net
57
2/1/2018 C# and .Net
Using ildasm.exe
• The Intermediate Language Disassembler utility (ildasm.exe) allows
you to load up any .NET assembly and investigate its contents,
including the associated manifest, CIL code, and type metadata.
• By default, ildasm.exe should be installed C:\Program
Files\Microsoft Visual Studio 8\SDK\v2.0\Bin
• File Open menu command and navigate to an assembly you wish
to explore
• ildasm.exe presents the structure of an assembly using a familiar
tree-view format
• Viewing CIL Code
• Viewing Type Metadata: to view the type metadata for the
currently loaded assembly, press Ctrl+M
• Viewing Assembly Metadata: To viewing the contents of the
assembly’s manifest, simply double-click the MANIFEST icon

58
2/1/2018 C# and .Net
The Platform-Independent Nature of .NET

• When Microsoft released the C# programming


language and the .NET platform, it also crafted a set of
formal documents that described the syntax and
semantics of the C# and CIL languages, the .NET
assembly format, core .NET namespaces, and the
mechanics of a hypothetical .NET runtime engine
• These documents have been submitted to European
Computer Manufacturers Association. International as
official international standards
– ECMA-334: The C# Language Specification
– ECMA-335: The Common Language Infrastructure (CLI)

59
2/1/2018 C# and .Net
Partitions of Meaning in Life
ECMA-335

Partition I: Describes the overall architecture of the CLI, including the


Architecture rules of the CTS and CLS, and the mechanics of the .NET
runtime engine
Partition II: Describes the details of .NET metadata
Metadata
Partition III: CIL Describes the syntax and semantics of CIL code

Partition IV: Gives a high-level overview of the minimal and complete


Libraries class libraries that must be supported by a .NET distribution.

Partition V: A collection of “odds and ends” details such as class library


Annexes design
guidelines and the implementation details of a CIL compiler

60
2/1/2018 C# and .Net
Questions
1. What are the building blocks of .NET framework? Explain their
relationship with a neat block diagram. Explain the CTS, in detail.

2. Explain the CLR. Illustrate the workflow that takes place between the
source code, given .NET compiler and the .NET execution engine. What is
the role of .NET type Metadata? Give an example

1. Explain the complexities found in the technologies prior to .NET. Briefly


describe. Explain how .NET attempts to simply the same.

2. Explain the formal definitions of all CTS types.


3. List and explain the intrinsic CTS data types and .NET namespaces in C#.

4. What is an assembly? Explain each component of an assembly.


Differentiate between single file and multi file assembly.
5. Write a note on .NET namespaces.

You might also like