Docsity

VTU 7TH SEM CSE C# PROGRAMMING & .NET NOTES 10CS761, Study notes of Computer Engineering and Programming

Toggle sidebar
bg1
C# PROGRAMMING AND .NET
Subject Code: 10IS761/10CS761 I.A. Marks : 25
Hours/Week : 04 Exam Hours: 03
Total Hours : 52 Exam Marks: 100
PART – A
UNIT – 1 6 Hours
The Philosophy of .NET: Understanding the Previous State of Affairs, The.NET Solution, The Building Block of
the .NET Platform (CLR,CTS, and CLS), The Role of the .NET Base Class Libraries, What C# Brings to the Ta ble,
An Overview of .NET Binaries (aka Assemblies), the Role of the Common Intermediate Language, The Role of
.NET Type Metadata, The Role of the assembly Manifast, Compiling CIL to Platform – Specific Instructions,
Understanding the Common Type System, Intrinsic CTS Data Types, Understanding the Common Languages
Specification, Understanding the Common Language Runtime A tour of the .NET Namespaces, Increasing Your
Namespace Nomenclature, Deploying the .NET Runtime.
UNIT – 2 6 Hours
Building C# Applications: The Role of the Command Line Complier (csc.exe), Building C# Application using
csc.exe Working with csc.exe Response Files, Generating Bug Reports, Remaining g C# Complier Options, The
Command Line Debugger (cordbg.exe) Using the, Visual studio .NET IDE, Other Key Aspects of the VS.NET IDE,
C# “Preprocessor:” Directives, an Interesting Aside: The System. Environment Class
UNIT – 3 8 Hours
C# Language Fundamentals: The Anatomy of Basic C# Class, Creating objects: Constructor Basics, The
Composition of a C# Application, Default assignment and Variable Scope, The C# Member Initialisation Syntax,
Basic Input and Output with the Console Class, Understanding Value Types and Reference Types, The Master
Node: System, Object, The System Data Types (and C# Aliases), Converting Between Value Types and Reference
Types: Boxing and Unboxing, Defining Program Constants, C# Iteration Constructs, C# Controls Flow Constructs,
The Complete Set of C# Operators, Defining Custom Class Methods, Understating Static Methods, Methods
Parameter Modifies, Array Manipulation in C#, String Manipulation in C#, C# Enumerations, Defining Structures in
C#, Defining Custom Namespaces.
UNIT – 4 6 Hours
Object- Oriented Programming with C#: Forms Defining of the C# Class, Definition the “Default Public
Interface” of a Type, Recapping the Pillars of OOP, The First Pillars: C#’s Encapsulation Services, Pseudo-
Encapsulation: Creating Read-Only Fields, The Second Pillar: C#’s Inheritance Supports, keeping Family Secrets:
The “ Protected” Keyword, Nested Type Definitions,The Third Pillar: C #’s Polymorphic Support, Casting Between
.
PART – B
UNIT – 5 6 Hours
Exceptions and Object Lifetime: Ode to Errors, Bugs, and Exceptions, The Role of .NET Exception Handing, the
System. Exception Base Class, Throwing a Generic Exception, Catching Exception, CLR System – Level
Exception(System. System Exception), Custom Application-Level Exception(System. System Exception), Handling
Multiple Exception, The Family Block, the Last Chance Exception Dynamically Identifying Application – and
System Level Exception Debugging System Exception Using VS. NET, Understanding Object Lifetime, the CIT of
“new’, The Basics of Garbage Collection,, Finalization a Type, The Finalization Process, Building an Ad Hoc
Destruction Method, Garbage Collection Optimizations, The System. GC Type.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64
Discount

On special offer

Partial preview of the text

Download VTU 7TH SEM CSE C# PROGRAMMING & .NET NOTES 10CS761 and more Study notes Computer Engineering and Programming in PDF only on Docsity!

C# PROGRAMMING AND .NET

Subject Code: 10IS761/10CS761 I.A. Marks : 25 Hours/Week : 04 Exam Hours: 03 Total Hours : 52 Exam Marks: 100

PART – A

UNIT – 1 6 Hours The Philosophy of .NET : Understanding the Previous State of Affairs, The.NET Solution, 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, An Overview of .NET Binaries (aka Assemblies), the Role of the Common Intermediate Language, The Role of .NET Type Metadata, The Role of the assembly Manifast, Compiling CIL to Platform – Specific Instructions, Understanding the Common Type System, Intrinsic CTS Data Types, Understanding the Common Languages Specification, Understanding the Common Language Runtime A tour of the .NET Namespaces, Increasing Your Namespace Nomenclature, Deploying the .NET Runtime.

UNIT – 2 6 Hours Building C# Applications: The Role of the Command Line Complier (csc.exe), Building C# Application using csc.exe Working with csc.exe Response Files, Generating Bug Reports, Remaining g C# Complier Options, The Command Line Debugger (cordbg.exe) Using the, Visual studio .NET IDE, Other Key Aspects of the VS.NET IDE, C# “Preprocessor:” Directives, an Interesting Aside: The System. Environment Class

UNIT – 3 8 Hours C# Language Fundamentals: The Anatomy of Basic C# Class, Creating objects: Constructor Basics, The Composition of a C# Application, Default assignment and Variable Scope, The C# Member Initialisation Syntax, Basic Input and Output with the Console Class, Understanding Value Types and Reference Types, The Master Node: System, Object, The System Data Types (and C# Aliases), Converting Between Value Types and Reference Types: Boxing and Unboxing, Defining Program Constants, C# Iteration Constructs, C# Controls Flow Constructs, The Complete Set of C# Operators, Defining Custom Class Methods, Understating Static Methods, Methods Parameter Modifies, Array Manipulation in C#, String Manipulation in C#, C# Enumerations, Defining Structures in C#, Defining Custom Namespaces.

UNIT – 4 6 Hours Object- Oriented Programming with C#: Forms Defining of the C# Class, Definition the “Default Public Interface” of a Type, Recapping the Pillars of OOP, The First Pillars: C#’s Encapsulation Services, Pseudo- Encapsulation: Creating Read-Only Fields, The Second Pillar: C#’s Inheritance Supports, keeping Family Secrets: The “ Protected” Keyword, Nested Type Definitions,The Third Pillar: C #’s Polymorphic Support, Casting Between .

PART – B

UNIT – 5 6 Hours Exceptions and Object Lifetime: Ode to Errors, Bugs, and Exceptions, The Role of .NET Exception Handing, the System. Exception Base Class, Throwing a Generic Exception, Catching Exception, CLR System – Level Exception(System. System Exception), Custom Application-Level Exception(System. System Exception), Handling Multiple Exception, The Family Block, the Last Chance Exception Dynamically Identifying Application – and System Level Exception Debugging System Exception Using VS. NET, Understanding Object Lifetime, the CIT of “new’, The Basics of Garbage Collection,, Finalization a Type, The Finalization Process, Building an Ad Hoc Destruction Method, Garbage Collection Optimizations, The System. GC Type.

UNIT – 6 6 Hours Interfaces and Collections: Defining Interfaces Using C# Invoking Interface Members at the object Level, Exercising the Shapes Hierarchy, Understanding Explicit Interface Implementation, Interfaces As Polymorphic Agents, Building Interface Hierarchies, Implementing, Implementation, Interfaces Using VS .NET, understanding the IConvertible Interface, Building a Custom Enumerator (IEnumerable and Enumerator), Building Cloneable objects (ICloneable), Building Comparable Objects ( I Comparable ), Exploring the system. Collections Namespace, Building a Custom Container (Retrofitting the Cars Type).

UNIT – 7 8 Hours Callback Interfaces, Delegates, and Events, Advanced Techniques: Understanding Callback Interfaces, Understanding the .NET Delegate Type, Members of System. Multicast Delegate, The Simplest Possible Delegate Example, , Building More a Elaborate Delegate Example, Understanding Asynchronous Delegates, Understanding (and Using)Events. The Advances Keywords of C#, A Catalog of C# Keywords Building a Custom Indexer, A Variation of the Cars Indexer Internal Representation of Type Indexer. Using C# Indexer from VB .NET. Overloading operators, The Internal Representation of Overloading Operators, interacting with Overload Operator from Overloaded- Operator- Challenged Languages, Creating Custom Conversion Routines, Defining Implicit Conversion Routines, The Internal Representations of Customs Conversion Routines

UNIT – 8 6 Hours Understanding .NET Assembles: Problems with Classic COM Binaries, An Overview of .NET Assembly, Building a Simple File Test Assembly, A C#. Client Application, A Visual Basic .NET Client Application, Cross Language Inheritance, Exploring the CarLibrary’s, Manifest, Exploring the CarLibrary’s Types, Building the Multifile Assembly, Using Assembly, Understanding Private Assemblies, Probing for Private Assemblies (The Basics), Private A Assemblies XML Configurations Files, Probing for Private Assemblies ( The Details), Understanding Shared Assembly, Understanding Shared Names, Building a Shared Assembly, Understanding Delay Signing, Installing/Removing Shared Assembly, Using a Shared Assembly

Text Books:

  1. Andrew Troelsen: Pro C# with .NET 3.0, Special Edition, Dream tech Press, India, 2007. Chapters: 1 to 11 (up to pp.369)
  2. E. Balagurusamy: Programming in C#, 5th^ Reprint, Tata McGraw Hill, 2004. (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)

It is literally true that you can succeed best and quickest by helping others to succeed.

UNIT 1: THE PHILOSOPHY OF .NET

UNDERSTANDING THE PREVIOUS STATE OF AFFAIRS

Life as a C Programmer

  • C is a very complex language because the programmers were forced to deal with → manual memory management → ugly pointer arithmetic → ugly syntactic-constructs
  • C is a structured language and so lacks the benefits provided by object-oriented approach.
  • When thousands of global-functions & data-types defined by the Win32 API are combined to a difficult language like C, bugs will increase rapidly. Life as a C++ Programmer
  • Though C++ provides OOPs concepts like encapsulation, inheritance & polymorphism, C++ programming remains a difficult & error-prone experience, given its historical roots in C. Life as a Visual Basic 6.0 Programmer
  • VB6 is popular due to its ability to build → complex user interfaces → code libraries & → simpler data access logic
  • The major downfall of VB is that it is not a fully object-oriented language, but rather "object- aware". For example, → It does not allow to establish "is-a" relationships between types → It does not support the ability to build multi-threaded applications → It has no support for parameterized class construction Life as a Java Programmer
  • Java has greater strength because of its platform independence nature.
  • Main problem with using Java: “we must use Java front-to-back during development cycle”.
  • Pure java is simply not appropriate for graphically intensive applications due to its slow execution-speed.
  • Java provides a limited ability to access non-Java APIs and hence, there is little support for true cross-language integration. Life as a Windows-DNA Programmer
  • The popularity of Web-applications is ever expanding. Sadly, building a web-application using COM-based Windows-DNA is quite complex.
  • Some of this complexity is because Windows-DNA requires use of numerous languages like ASP, HTML, XML, JavaScript, VBScript, ADO etc.
  • Many of these technologies are completely unrelated from a syntactic-point of view.

Positive thinking will let you do everything better than negative thinking will.

THE .NET SOLUTION

Full Interoperability with Existing Win32code

  • Existing COM binaries can inter-operate with newer .NET binaries & vice versa.
  • Also, PInvoke(Platform invocation) can be used to invoke raw C-based functions from managed-code. Complete & Total Language Integration
  • .NET supports → cross language inheritance → cross language exception-handling & → cross language debugging A Common Runtime Engine Shared by all .NET-aware languages
  • Main feature of this engine is "a well-defined set of types that each .NET-aware language understands". A Base Class Library that → protects the programmer from the complexities of raw API calls → offers a consistent object-model used by all .NET-aware languages A Truly Simplified Deployment Model
  • Under .NET, there is no need to register a binary-unit into the system-registry.
  • .NET runtime allows multiple versions of same *.dll to exist in harmony on a single machine. No more COM plumbing IClasFactory, IUnknown, IDispatch, IDL code and the evil VARIANT compliant data-types have no place in a native .NET binary.

C# LANGUAGE OFFERS THE FOLLOWING FEATURES

  • No pointer required. C# programs typically have no need for direct pointer manipulation.
  • Automatic memory management through garbage-collection. Given this, C# does not support a delete keyword.
  • Formal syntactic-constructs for enumerations, structures and class properties.
  • C++ like ability to overload operators for a custom type without the complexity.
  • Full support for interface-based programming techniques.
  • Full support for aspect-based programming techniques via attributes. This brand of development allows to assign characteristics to types and their members to further qualify the behavior.

Achievement seems to be connected with action. Successful men and women keep moving. They make mistakes, but they don't quit.

AN OVERVIEW OF .NET BINARIES

  • Regardless of which .NET-aware language we choose (like C#, VB.NET, VC++.NET etc), →.NET binaries take same file-extension (.exe or .dll) →.NET binaries have absolutely no internal similarities (Figure: 1-2)
  • .NET binaries do not contain platform-specific instruction but rather platform-agnostic "Common Intermediate Language (CIL)”.
  • When .NET binary is created using a .NET-aware compiler, the resulting module is bundled into an assembly.
  • An assembly is a logical grouping of one or more related modules (i.e. CIL, metadata, manifest) that are intended to be deployed as a single unit.
  • The assembly contains
    1. CIL-code which is not compiled to platform-specific instructions until absolutely-necessary. Typically "absolutely-necessary" is the point at which "a block of CIL instructions" are referenced for use by the runtime-engine.
    2. Metadata that describes the characteristics of every "type" living within the binary.
    3. Manifest: Assemblies themselves are also described using metadata, which is termed as manifest_._ The manifest contains information such as → name of assembly/module → current version of assembly → list of files in assembly → copyright information → list of all externally referenced assemblies required for proper execution

Managed code & unmanaged code

  • C# produces the code that can execute within the .NET runtime. The code targeting the .NET runtime is called as managed-code.
  • Conversely, code that cannot be directly hosted by the .NET runtime is termed unmanaged-code.

Success is the maximum utilization of the ability that you have.

SINGLE-FILE AND MULTI-FILE ASSEMBLIES

  • Single-file assemblies contain all the necessary CIL, metadata and manifest in a single well-defined package. (Package means folder).
  • On the other hand, multi-file assemblies are composed of numerous .NET binaries, each of which is termed a module.
  • In a multiple assembly, one of the module (termed as primary module) must contain the assembly-manifest. The other related modules contain a module-level manifest, CIL and type metadata.
  • The primary-module maintains the set of required secondary-modules within the assembly manifest.
  • Multifile assemblies are used when different modules of the application are written in different languages.
  • Q: Why would we choose to create a multi-file assembly? Ans: Multifile assemblies make the downloading process more efficient. They enable us to store the rarely used types in separate modules and download them only when needed.

ROLE OF CIL

  • CIL is a language that sits above any particular platform-specific instruction set.
  • Regardless of which .NET-aware language we choose (like C#, VB.NET, VC++.NET etc), the associated compiler produces CIL instructions.
  • Once the C# complier (csc.exe) compiles the source code file, we end up with a single file *.exe assembly that contains a manifest, CIL instructions and metadata describing each aspect of the program. Benefits of CIL
  • Language Integration : Each .NET-aware language produces the same underlying-CIL. Therefore, all .NET-aware languages are able to interact within a well-defined binary arena.
  • Since CIL is platform-agnostic, the .NET runtime is poised to become a platform-independent architecture. Thus, .NET has the potential to allow us to develop an application in any language and have it run on any platform.

Desire is the starting point of all achievement, not a hope, not a wish, but a keen pulsating desire which transcends everything.

UNDERSTANDING THE CTS

  • A given assembly may contain any number of distinct “types”.
  • In the world of .NET, “type” is simply a generic term used to refer to a member from the set {class, structure, interface, enumeration, delegate}.
  • CTS → fully describes all possible data-types & programming constructs supported by the runtime → specifies how these entities can interact with each other & → details of how they are represented in the metadata format
  • When we wish to build assemblies that can be used by all possible .NET-aware languages, we need to conform our exposed types to the rules of the CLS.

CTS Class Types

  • Class consists of number of members (methods, constructor) and data points (fields).
  • CTS allow a given class to support virtual and abstract members that define a polymorphic interface for derived class.
  • Classes may only derive from a single base class; multiple inheritances are not allowed for class.
  • In C#, classes are declared using the class keyword. For example, // A C# class type public class Calc { public int Add(int x, int y) { return x + y; } }

Class Characteristic

Meaning

Is the class “sealed” or not?

Sealed classes cannot function as a base class to other classes.

Does the class implement any interfaces?

An interface is a collection of abstract members that provide a contract between the object and object-user. The CTS allows a class to implement any number of interfaces. Is the class abstract or concrete?

Abstract classes cannot be directly created, but are intended to define common behaviors for derived types. Concrete classes can be created directly. What is the “visibility” of this class?

Each class must be configured with a visibility attribute. Basically, this feature defines if the class may be used by external assemblies, or only from within the defining assembly (e.g., a private helper class).

CTS Interface Type

  • Interface is a named collection of abstract member definitions, which may be supported by a given class or structure.
  • Interfaces do not derive from a common base type (not even System.Object).
  • When a class/structure implements a given interface, we are able to request access to the supplied functionality using an interface-reference (in a polymorphic manner).
  • When we create custom interface using a .NET-aware language, the CTS allows a given interface to derive from multiple base interfaces.
  • In C#, interface types are defined using the interface keyword, for example: // A C# interface type. public interface IDraw { void Draw(); }

The secret of happiness is to count your blessings while others are adding up their troubles.

CTS Structure Types

  • A structure can be thought of as a lightweight type having value-semantics.
  • Structure may define any number of parameterized constructors.
  • All structures are derived from a common base class: System.ValueType.
  • This base class configures a type to behave as a stack-allocated entity rather than a heap-allocated entity.
  • Structures can implement any number of interfaces.
  • Structures may not become a base type to any other classes or structures. Therefore structures are explicitly sealed.
  • In C#, structure is declared using the struct keyword. For example, // 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("({0}, {1})", xPos, yPos); } }

CTS Enumeration Types

  • Enumeration is used to group name/value pair under a specific name.
  • By default, the storage used to hold each item is a System.Int32 (32-bit integer).
  • Enumerated types are derived from a common base class, System.Enum This base class defines a number of interesting members that allow extracting, manipulating, and transforming the underlying name/value pairs programmatically.
  • Consider an example of creating a video-game application that allows the player to select one of three character categories (Wizard, Fighter, or Thief). Rather than keeping track of raw numerical values to represent each possibility, we could build a custom enumeration as: // A C# enumeration public enum playertype { wizard=10, fighter=20, thief= };

CTS Delegate Types

  • Delegates are the .NET equivalent of a type-safe C-style function pointer.
  • The key difference is that a .NET delegate is a class that derives from System.MulticastDelegate, rather than a simple pointer to a raw memory address.
  • Delegates are useful when we wish to provide a way for one entity to forward a call to another entity.
  • Delegates provide intrinsic support for multicasting, i.e. forwarding a request to multiple recipients.
  • They also provide asynchronous method invocations.
  • They provide the foundation for the .NET event architecture.
  • In C#, delegates are declared using the delegate keyword as shown in the following example: // 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);

The poor, the unsuccessful, the unhappy, the unhealthy are the ones who use the word tomorrow the most.

UNDERSTANDING THE CLR

  • The runtime can be understood as a collection of external services. These services are required to execute a given compiled unit-of-code. (Figure: 1-3)
  • .NET runtime provides a single well-defined runtime layer that is shared by all .NET aware languages.
  • The heart of CLR is physically represented by an assembly named mscoree.dll (Common Object Runtime Execution Engine).
  • When an assembly is referenced for use, mscoree.dll is loaded automatically, which in turn loads the required assembly into memory.
  • Runtime-engine → places the type in memory → compiles the associated CIL into platform-specific instruction → performs any security checks and → then executes the code
  • In addition, runtime-engine is responsible for → resolving location of an assembly and → finding requested type within binary by reading contained-metadata → interacting with the types contained within the BCLs
  • mscorlib.dll assembly contains a large number of core types. The core types encapsulate a wide variety of common programming tasks used by all .NET languages.

There's always a way - if you're committed.

A TOUR OF THE .NET NAMESPACES

  • C# language does not come with a pre-defined set of language-specific classes.
  • There is no C# class library. Rather, C# developers use existing types supplied by .NET framework.
  • Advantage of namespaces: Any language targeting the .NET runtime makes use of same namespaces and same types as a C# developer.
  • Namespace refers to grouping semantically related types (classes, enumerations, interfaces, delegates and structures) under a single name. For example, System.IO namespace contains file I/O related types System.Data namespace defines basic database types, and so on //Hello world in C#

using System ; public class MyApp { public static void Main() { Console.WriteLine("hi from C#"); } }

'Hello world in VB.NET

Imports System Public Module MyApp Sub Main() Console.WriteLine("hi from VB.NET") End Sub End Module

  • In above code, each language is making use of “Console” class defined in the “System” namespace.
  • "System" namespace provides a core body of types that we will need to use as a .NET developers.
  • We cannot build any sort of functional C# application without making a reference to the "System" namespace.
  • “System" is the root namespace for numerous other .NET namespaces.

.NET NAMESPACES

System In this, we find numerous low-level classes dealing with primitive types, mathematical manipulations, garbage collection, exceptions and predefined attributes. System.Collections This defines a number of stock container objects (ArrayList, Queue, etc) as well as base types and interfaces that allow us to build customized collections. System.Data.OleDb These are used for database manipulation. System.Diagnostics In this, we find numerous types that can be used by any .NET-aware language to programmatically debug and trace our source code. System.Drawing System.Drawing.Printing In this, we find numerous types wrapping GDI+ primitives such as bitmaps, fonts, icons, printing support, and advanced graphical rendering support. System.IO This includes file IO and buffering. System.Net This contains types related to network programming (requests/responses, sockets, end points) System.Security In this, we find numerous types dealing with permissions, cryptography and so on. System.Xml This contains numerous types that represent core XML primitives and types used to interact with XML data. System.Threading This deals with threading issues. In this, we will find types such as Mutex, Thread and Timeout.

Other people's opinion of you does not have to become your reality.

INTRINSIC CTS DATA TYPES

.NET Base Type (CTS Data Type)

VB.NET

Keyword

C# Keyword 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 __int System.UInt16 UShort ushort unsigned short 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

EXERCISES

  1. Briefly discuss state of affairs that eventually led to .NET platform. (8)
  2. Explain .NET solution. (4)
  3. What are the key features of C#? (4)
  4. With a neat diagram, explain basic building block of .NET framework. (8)
  5. What do you mean by Base class library? Explain. (2)
  6. Explain the concept of .NET binaries. (6)
  7. Bring out important differences b/w single and multifile assemblies. (4)
  8. Explain the role of CIL and the benefits of CIL. (4)
  9. Explain the role of JIT compiler. (6)
  10. What are basic CTS data types? Explain. (8)
  11. Explain common type system in detail. (6)
  12. Explain with a neat diagram, the workflow that takes place between your source code, a given .NET complier and the .NET execution engine. (8)
  13. What are namespaces? List and explain the purpose of at least five namespaces. (6)

Your future is created by what you do today, not tomorrow.

UNIT 2: BUILDING C# APPLICATIONS

BUILDING A C# APPLICATION USING csc.exe

  • Consider the following code: using System; class TestApp { public static void Main() { Console.WriteLine("Testing 1 2 3"); } }
  • Once finished writing the code in some editor, save the file as TestApp.cs
  • To compile & run the program, use the following command-set: Output: C:\CSharpTestApp> csc TestApp.cs C:\CSharpTestApp> TestApp.exe Testing 1 2 3
  • List of Output Options of the C# Compiler: /out : This is used to specify name of output-file to be created. By default, name of output-file is same as name of input-file. / target:exe :This builds an executable console application. This is the default file output-type. /target:library :This option builds a single-file assembly. /target:module :This option builds a module. Modules are elements of multi-file assemblies. /target:winexe :Although we are free to build windows-based applications using /target:exe flag, this flag prevents an annoying console window from appearing in the background.

REFERENCING EXTERNAL ASSEMBLIES

  • Consider the following code: using System; using System.Windows.Forms; class TestApp { public static void Main() { MessageBox.Show("Hello.. ."); } }
  • As we know, mscorlib.dll is automatically referenced during the compilation process. But if we want to disable this option, we can specify using /nostdlib flag.
  • Along with "using" keyword, we must also inform compiler which assembly contains the referenced namespace. For this, we can use the /reference(or /r) flag as follows: csc /r:System.Windows.Forms.dll TestApp.cs
  • Now, running the application will give the output as –

The hardest thing to learn in life is which bridge to cross and which to burn.

THE DEFAULT RESPONSE FILE (csc.rsp)

  • C# compiler has an associated default response-file(csc.rsp), which is located in the same directory as csc.exe itself (e.g., C:\Windows\Microsoft.NET\Framework\v2.0.50215).
  • If we open this file using Notepad, we can see that numerous .NET assemblies have already been specified using the /r: flag.
  • When we are building our C# programs using csc.exe, this file will be automatically referenced, even if we provide a custom *.rsp file.
  • Because of default response-file, the current Test.exe application could be successfully compiled using the following command set csc /out:Test.exe *.cs
  • If we wish to disable the automatic reading of csc.rsp, we can specify the /noconfig option: csc @Test.rsp /noconfig

GENERATING BUG REPORTS

  • /bugreport flag allows to specify a file that will be populated with any errors encountered during the compilation-process. The syntax for using this flag is– csc /bugreport: bugs.txt *.cs
  • We can enter any corrective information for possible errors in the program, which will be saved to the specified file (i.e. bugs.txt).
  • Consider the following code with an error (bug): public static void Main() { HelloMessage h=new HelloMessage(); h.Speak() // error occurs because ; is missing }
  • When we compile this file using /bugreport flag, the error message will be displayed and corrective action is expected as shown – Test.cs (23, 11): Error CS1002: ; expected ----------------- _Please describe the compiler problem: __
  • Now if we enter the statement like “ FORGOT TO TYPE SEMICOLON” then, the same will be stored in the ‘bugs.txt’ file.

With better awareness come better choices. And with better choices, you’ll see better results

OPTIONS OF THE C# COMMAND LINE COMPILER

/target This is used to specify format of output-file. /out This is used to specify name of output-file. /nostdlib This is used to prevent automatic importing of core .NET library ‘mscorlib.dll’. /reference This is used to reference an external assembly. @ This allows to specify a response-file used during compilation. /noconfig This is used to prevent use of response-files during the current compilation. /bugreport This is used to build text-based bug-reports for the current compilation. /main This is used to specify which Main() method to use as the program's entry point, if multiple Main() methods have been defined in the current *.cs file-set. /? Or /help This prints out list of all command-line flags of compiler. /addmodule This is used to specify modules to be added into a multi-file assembly. /nologo This is used to suppress banner-information when compiling the file. /debug This forces compiler to emit debugging-information. /define This is used to define pre-processor symbols. /optimize This is used to enable/disable optimizations. /warn This is used to set warning-level for the compilation cycle. /doc This is used to construct an XML documentation-file. /filealign This is used to specify size of sections in output-file. /fullpaths This is used to specify absolute path to the file in compiler output. /incremental This is used to enable incremental compilation of source-code files. /lib This is used to specify location of assemblies referenced via /reference. /linkresource This is used to create a link to a managed-resource. /baseaddress This is used to specify preferred base-address at which to load a *.dll /checked This is used to specify the code-page to use for all source-code files in the compilation.