29

Click here to load reader

C# Introduction Notes

Embed Size (px)

Citation preview

Page 1: C# Introduction Notes

Philosophy of .NET

History

C/Win32 Programmer* Developing s/w’s for windows OS involved using C pgmng language in conjunction with windows API.* Using C pgms & employing raw windows API is a complex job of pgmng.* C pgms have to do manual memory management, complex pointer arithmetic, C has complex syntactical constructs.* More over C is structured language and lacks the advantages of OOP.

C++/MFC pgmr* One vast improvement over C/Win32 pgmng is the use of C++ pgmng. C++ can be thought of as an Object oriented layer on top of C.* Although C++ supports 3 main pillars of OOP (Encapsulation, Polymorphism & Inheritance) they also have the complex nature of C such as manual memory management, complex pointer arithmetic etc.,* Despite its complexity, many C++ frame works exist such as MFC(Microsoft Foundation Classes). MFC is a group/collection of Win32 API’s, which facilitate the construction of windows applications.

VB 6.0 pgmr* VB is popular due to its ability to build complex user interface, code libraries, data access logic with very less complexity.* VB hides all the complexities from the pgmr. The main drawback of VB is that it is not object oriented language, rather is “object-aware” language.* VB 6.0 doesn’t allow pgmr to establish “is a” relationship between types, and also it doesn’t support multithreaded application to be developed.

Java pgmr* Java language is completely object oriented and has its syntactic roots in C++* Java’s strength is platform independence i.e a pgm can be written in one platform & executed in another.* Java supports its pgmr with a large no of predefined “package” that contain various class and interface definitions.* Although Java offers little hope of language independence, as this goes against the Java’s primary goal “ a single pgmng language for every need”.* Pure Java is not appropriate for many graphically/numerically intensive applications.

COM pgmr* COM stands for “Component Object Model”.* If a pgm is built in accordance with rule of COM, then a pgm is created which can be used in any other language.* C++ pgmrs can build COM classes that can be used by VB.* COM allows only has-a kind of relationship & does not provide any support for is-a kind of relationship.* COM is a dominant object model, it is very complex/difficult to develop the pgms using COM.

1

Page 2: C# Introduction Notes

Windows DNA pgmr* DNA stands for “Distributed iNternet Architecture”.* Due to the popularity of web, Microsoft has been adding more internet aware features into its family of OS.* Any web application can be developed under the hood of windows DNA. Windows DNA requires the use of numerous technologies like ASP .HTML, XML, Java Script, VB Script, COM etc., many of these languages differ greatly in their syntactic point of view.

.NET solution Below are some core features provided by .NET

* Full interoperability with Win 32 code* Complete & total language integration .NET allows cross-language inheritance, cross-language exception handling & cross-language debugging.* Common runtime engine shared by all .NET aware languages This runtime engine contains a well-defined set of types that each .NET language is aware of.* Base class library This moulds all the complexities of raw API calls and provides the pgmr a consistent object model.* Building blocks of .NET Three building blocks of .NET are termed as

1) CLR [Common Language Runtime]2) CTS [Common Type System]3) CLS [Common Language Specification]

1) CLR * From a pgmrs point of view .NET is a new runtime environment and a common base class library. * The runtime layer is properly referred to as the Common Language Runtime or CLR. Primary goal of CLR is to locate, load and manage .NET type on behalf of the pgmr. * CLR also takes care of a number of low-level details such as automatic memory management, language integration etc.,

2) CTS * CTS fully describes all possible data types and pgmng constructs supported by the runtime. Also, specifies how these entities can interact with each other. * CTS also details how they are represented in .NET metadata format.

3) CLS * CLS is a subset of rules that are present in CTS. * Defines a set of features that are common in different languages. * CLS compliance is especially important when creating s/w components that will be used by other languages. * If a pgm makes use of data types or pgmng construct that is outside of CLS, then those pgms cannot be used by other pgmng languages.

2

Page 3: C# Introduction Notes

Base class library* In addition to CLR, CTS & CLS .NET platform provides a base class library that is available to all .NET pgmng languages.* This base class encapsulates various primitives such as threads, file I/O, graphical pgmng, interaction with various hardware devices. etc.,

C# Language* Microsoft has developed a new language specification for .NET frame work called as C#. Syntactic structure of this language is very similar to Java. C# is a hybrid of numerous languages. C# language offers following features.

1) No pointer required: C# pgms typically does not need any pointer usage.2) Automatic memory management: C# does not support a delete keyword.3) Formal syntactic constructs for enumerations, structures & class properties.4) C++ like ability to overload the operators for accustom type.

* There are 2 categories of code that is existing 1) Managed code 2) Unmanaged code* Managed code are those that are executed under the control of CLR. These managed code’s are subjected to certain constraints and provides several benefits. Benefits, such as memory management, ability to mix languages, better security, support for version-control and a clean way for s/w components to interact.* Opposite of managed code is unmanaged code. Unmanaged code does not execute under CLR. All, windows pgm prior to creating of .NET is considered as unmanaged code.* Finally, C# pgm is a managed code & there is no restriction for these pgms to commingle with unmanaged code.

.NET Binaries/Assembly* An assembly is a file that is automatically generated by the compiler upon successful compilation of every .NET application.* It can be either a Dynamic Link Library or an executable file. It is generated only once for an application and upon each subsequent compilation the assembly gets updated.* An assembly contains Intermediate Language (IL) or Common Intermediate Language (CIL) code which is similar to Java byte code.* In the .NET language, it consists of metadata. Metadata enumerates the features of every “type” inside the assembly or the binary.

3

Base class libraryData access

Threading

GUI

File I/O

Security

Debugging

XML/SOAP

etc.,

Common Language RuntimeCommon Type System

Common Language Specification

Page 4: C# Introduction Notes

* In addition to metadata, assemblies also have a special file called Manifest. It contains information about the current version of the assembly and other related information.* In .NET, there are two kinds of assemblies, such as Single file & Multi file.* A Single file assembly contains all the required information (IL, Metadata and Manifest) in a single package. The majority of assemblies in .NET are made up of single file assemblies.* Multi file assemblies are composed of numerous .NET binaries or modules and are generated for larger applications. One of the assemblies will contain a manifest and others will have IL and Metadata instructions.* Main benefit of IL is its power to integrate with all .NET languages. This is because all .NET languages produce the same IL code upon successful compilation; hence, they can interact with each other very easily.

MSIL – MicroSoft Intermediate Language

METADATA* .NET metadata, in the Microsoft .NET framework, refers to certain data structures embedded within the Common Intermediate Language code that describes the high-level structure of the code.* Metadata describes all classes and class members that are defined in the assembly, and the classes and class members that the current assembly will call from another assembly.* Metadata for a method contains the complete description of the method, including the class (and the assembly that contains the class), the return type and all of the method parameters.* A .NET language compiler will generate the metadata and store this in the assembly containing the CIL. * When the CLR executes CIL it will check to make sure that the metadata of the called method is the same as the metadata that is stored in the calling method.* This ensures that a method can only be called with exactly the right number of parameters and exactly the right parameter types.

Common Intermediate Language* CIL is a language that is above any particular platform specific instruction set. Irrespective of any .NET aware language like C#, VB, COBOL etc., the associated compiler produces CIL instructions.Consider a C# pgm which will add & subtract 2 no’s

class calc{ public void Add(int x, int y)

{ Console.WriteLine(“{0} {1}”,(x+y),(x-y)); }}

4

C# Source code

Perl to Perl .NETSource code

COBOL to COBOL .NET Source code

C# compiler

Perl to Perl .NET compiler

COBOL to COBOL .NET

compiler

MSIL&

Metadata with file

Page 5: C# Introduction Notes

class Ex { public static void Main( ) {

calc a = new calc( ); a.Add(1,2);

} }

* Once the above C# pgm is compiled using C# compiler a single *.EXE assembly will be created which contains a manifest, CIL instruction & metadata describing each class Ex & class calc. Consider a VB .NET pgm which will add & subtract 2 no’s

class calc public Functoin Add(ByVal x as integer, ByVal y as integer)

Console.WriteLine(“{0} {1}”,(x+y),(x-y)) End FunctionEnd Class

Module Exsub Main( )

Dim c as new calcc.Add(1,2);

End subEnd Module

( In VB .NET module is like a class which contains only static members.)* Once the above VB .NET pgm is compiled in .NET framework using VB .NET aware compiler a single *.EXE assembly will be created which also contains a manifest, CIL instruction & metadata describing each class Ex & class calc.* The assembly of VB .NET pgm & assembly of C# pgm will be almost same. One advantage of compiling to CIL is language integration. In order to achieve language integration all .NET aware languages produce same CIL. Therefore all languages are able to interact within a well defined binary arena.

Converting CIL to platform-specific instructions* CIL contains only metadata, manifest & CIL instruction which are considered as platform independent instructions. The CIL instructions are converted to platform-specific instructions by an entity called as “just-in-time” compiler (JIT compiler) or Jitter.* Further a Jitter compiles CIL instructions into corresponding machine code & store the result in memory in a manner suited to the target OS.

CTS * CTS is a formal specification that describes how a given type (class, structure, interface etc.,) must be defined in order to be hosted by CLR. The formal definitions of all possible CTS types are as follows.

CTS class type* Every .NET aware language supports a class which is the cornerstone of OOP.* A class may contain any no of members (such as constructors, operators, properties, methods & events) & data points (fields).* CTS allows a given class to support virtual & abstract members that define a polymorphic interface for derived classes.* CTS classes are derived from a single base class.

5

Page 6: C# Introduction Notes

CTS Structure types* The concept of structures is also prevailing under CTS. A structure can be thought of as a light weight class type; which is considered as value data types.* CTS structures can have any no of parameterized constructors but not default constructor.* CTS structures are derived from a common base class “System.ValueType”. This base class makes it child class objects to acquire the memory on the stack rather than a heap.* CTS permits structures to implement any no of interfaces.* Structures cannot function as the base type to other classes or structures and are therefore explicitly “sealed”.

CTS interface types* Interfaces are nothing more than a named collection of abstract member definitions, which may be implemented by a class or structure.* Interfaces are the only one in .NET which do not derive from a common base type.* When a class or structure implements interfaces in its own way, then the method defined in the class or structure can be invoked using an interface reference in a polymorphic manner.

CTS enumeration types* Enumeration allow pgmr to group name/value pairs under a specific name.

Ex: enum color { RED, WHITE, BLUE};* By default, the storage used to hold each item is a System.Int32. However, it is possible to alter this storage also if needed.* Enumeration in CTS is derived from a common base class System.Enum, which contains a no of members that allow pgmrs to extract, manipulate & transform the underlying name/value at runtime.

CTS delegate types * Delegates are .NET equivalent for a C style function pointer. Difference is that a .NET delegate is a class that derives from “System.MulticastDelegate”, rather than a simple pointer to a raw memory address.* Further delegate provide intrinsic support for multicasting & asynchronous method invocations.

CLS* Different languages express the same pgmng constructs in different language specific terms.

Ex: String concatenation in C# is done using + operator String concatenation in VB is done using & operator

* Consider the 2 different functions in VB .NET & C# language whose return type is void.VB .NET C# public Sub Add( ) public void Add( ) …. { ….. } End Sub* Minor syntactic variations are seen in the 2 functions belonging to 2 different languages. These minor syntactic variations are inconsequential for .NET runtime. But, the respective compilers such as “vbc.exe” for VB .NET & “csc.exe” for C# are configured to emit the same CIL instruction set.* Languages can also differ with regard to their overall level of functionality.

Ex: C# language allows operator to be overloaded.VB .NET language will not allow overloading of operators.

* CLS is a set of guidelines that describe in detail, the minimal & complete set of features a given .NET-aware compiler must support to produce code that can be hosted by CLR.* At the same time the code can be accessed in a uniform manner by all languages that target the .NET platform. CLS is a subset of the full functionality defined by CTS.

6

Page 7: C# Introduction Notes

* CLS is a set of rules that compiler builders must conform to. All these rules are identified by their numbers such as CLS Rule 6.

CLR* .NET runtime provides a single well-defined runtime layer that is shared by all languages & platforms that are .NET aware.* .NET runtime is officially termed as CLR. CLR is the name given to an assembly named “mscoree.dll” (Microsoft Common Object Runtime Execution Engine). When as assembly is referenced for use mscoree.dll is loaded automatically, which in turn loads the required assembly into memory.* Runtime engine mscoree.dll is responsible for a no of tasks. This resolves the location of an assembly & finds the required type within the binary by reading the contained metadata.* Execution engine lays out the type in memory, compiles the associated CIL into platform-specific instructions & then executes the code.* In addition to loading custom assemblies & creating executable code, CLR will also interact with types contained within the .NET base class libraries.* The base class library has been broken into a no of discrete assemblies, the key binary is mscorlib.dll, which contains a large no of core type within it.

Fig: Workflow between source code, a .NET compiler & .NET execution engine

7

.NET Execution Engine (mscoree.dll)

Class loader

Jitter

Platform Specific Instructions

Execute the application

DLL or EXE Assembly (CIL, Metadata & Manifest)

.NET source code from some .NET aware langauge

Some .NETCompiler

Base Class Libraries(mscorlib.dll and so forth)

Page 8: C# Introduction Notes

Building C# application using CSC.EXE* CSC stands for “C Sharp Compiler” which converts C# source code to IL(Intermediate Langauge) form.* C# pgms can be executed directly on VS .NET IDE or can be executed directly in command prompt issuing the commands.* Some output options for C# compiler are as follows. These options allow the programmer to convert the code under consideration to console application, or a code library or a windows forms application etc.,

File output options Meaning/out Used to specify the name of the o/p file. By default, the name of o/p

file is same as the name of the input *.CS file containing the source code.

/target:exe Builds *.exe console application. This is the default file o/p type./target:library Builds a single file *.dll assembly/target:module Builds a module: Modules are elements of multi-file assemblies./target:winexe Builds a winexe application

Ex: C:\CSC /target:exe Hello.CS

Referencing external assemblies* When “using System”, line is written in a C# pgm the mscorlib.dll is automatically referenced during the compilation process.

Ex: Test.cs using System;using System.Windows.Forms;class Test {

public static void Main( ){ Console.WriteLine(“Testing 1 2 3”); MessageBox.Show(“Hello…”);

}}

* As seen in the program Windows.Form class has been included in it. It is not enough just to include the namespace System.Windows.Form class, but the CSC.EXE must be informed during compilation time about which assembly contains the referenced namespace.* This information can be passed to CSC using /reference flag written shortly as /r. So, the command is written as.

C:\ CSC /r : System.Windows.Forms.Dll Test.cs

Compiling Multiple Source Files* C# pgms are usually implemented in a multiple source code file, rather than a single source code file.Ex:

8

Hellomsg.csusing System;using System.Windows.Forms;class Hellomsg { public void speak( ) { MessageBox.Show(“Hello…”); }}

Test.csusing System;class Test { public static void Main( ) { Console.WriteLine(“Testing 1 2 3”); Hellomsg h = new Hellomsg( ); h.speak( ); }}

Page 9: C# Introduction Notes

* Above 2 files are compiled as shown below.

C:\CSC /r : System.Windows.Forms.dll Test.cs Hellomsg.cs

* As an alternative, if a directory contains many *.CS files which are considered as a part of the solution pgm, then a command can be given as below using wild character (*)

C:\CSC /r : System.Windows.Forms.dll /out : Test.exe *.CS

As shown above, when wild character * is used it is a rule to specify the o/p file name using the flag /out. Above command includes all *.CS files present in the current directory.

* In order to refer multiple external assemblies the command is as shown below. C:\ CSC /r : System.Windows.Forms.dll; System.Drawing.dll /out : Test.exe *.CS

Response files* If a complex C# application is to be built, which contains numerous *.CS files & numerous references for it then defining all these in command prompt using flags is difficult.* To overcome this problem response files are used. C# response files has the extension as *.rsp, it contains all the instructions to be used during compilation of current build. Comments can be written within response files using # symbol. Ex:

* Above file exec.rsp is conveyed to CSC.exe as a response file suing the symbol @ as shown below.C:\ CSC @exec.rsp

* There is a default response file in C# named as csc.rsp, when C# pgms are built using CSC.exe, this file will be automatically referenced.

Generating bug reportsC# compiler provides a flag named /bugreport. This flag allows to specify a file name; which contains various statistics regarding current build; including any errors encountered during the compilation process.

Ex: C:\ CSC /bugreport : bugs.txt Test.cs

Command Line Debugger* .NET provides a command line debugger named “cordbg.exe”. This option allows programmer to run .NET assemblies under debug mode. Cordbg is associated with several flags which assists a programmer in debugging a C# pgms in console mode. Some of the flags are as listed below.

9

Test.csusing System;class Test { public static void Main( ) { Console.WriteLine(“Hello”); } }

exec.rsp# This is response file for Test.cs

/target : exe /out : Test.exe

Page 10: C# Introduction Notes

Command Line Flag of cordbg.exe

Meaning

b[reak] Set or display current breakpointsdel[ete] Remove one or more breakpointsex[it] Exit the debuggerg[o] Continue debugging the current process until hitting next

breakpointsi Step into the next lineo[ut] Step out of the current functionSo Step over the next linep[rint] Print all loaded variables (local, arguments etc.,)

* Before debugging an application using cordbg.exe; first step is to generate symbolic debugging symbols for the application by specifying /debug flag of csc.exe.

Ex : C: \ CSC @test.rsp /debug

Above command generates a new file named test.pdb. *.pdb file contains associated symbols for debugging along with the source code. Once test.pdb file is generated, the assembly (test.exe) must be opened using cordbg.exe and test.pdb will be automatically loaded.

Ex: c:\ cordbg.exe testapp.exe Debugging starts and any flags listed above can be used to debug the application.

Using Visual Studio .NET IDE* Visual Studio .NET IDE allows programmer to build applications using any number of .NET-aware languages like C#, J#, VB .NET, MFC, ATL or traditional C-based Win 32 applications.

Creating VS .NET Project Solution

* Different kinds of C# project workspaces can be created in VS .NET IDE. When “New Project” button is clicked from the File menu several project workspaces are visible depending on the kind of language we choose. Some, of them are listed as below.

Project Type MeaningWindows Application This project type represents a Windows Forms application.Class Library Allows to build a single file assembly (*.dll)Windows Control Library

Allows to build a single file assembly (*.dll) that contains custom Windows Forms Controls

Web Control Library Allows to build customized web controls.Console Application Console based applicationsWindows Services Allows to build NT/2000 services. These are background

worker applications that are launched during the OS boot process.

10

Page 11: C# Introduction Notes

Different files associated with .NET application* When a console application has been selected; a new folder of the same name will be created that contains a number of starter files and project subdirectories that are enlisted as below

Generated Item Meaning\bin\Debug This folder contains debug version of

compiled .NET assembly\obj\* Under \obj there are several subfolders used by

VS .NET during the compilation process.*.ico An *.ico file used to specify the icon for the

current programAssemblyInfo.cs This file allows to establish assembly-level

attributes for current project.*.cs Initial class file*.csproj Represents a C# project that is loaded into a given

solution*.sln Represents current VS .NET solution (Collection

of individual projects)

Solution Explorer Window* Any application is built as a project in VS .NET. Each project contains any number of source code files, external references, and resources that constitute the application as a whole.* A “solution” is a collection of one or more “projects”. Using solution explorer windows all such items can be viewed & opened.

* Solution explorer window also provides a class view tab, which shows the object-oriented view of the project. Advantage of this is if the programmer double clicks on a given icon, control will be placed in the definition of it.

* When right-clicked on a given item a context-sensitive pop-up menu will be activated. This menu allows programmer to access a number of tools that allows to configure the current project settings and sort items in a variety of ways.

11

Solution Explorer

Solution ‘VSapp’ (Project)+ VSapp Properties References *.cs

Class View - VSapp

Ex [class name] Methods & data will be listed here

Page 12: C# Introduction Notes

Referencing External Assemblies via VS .NET * Several assemblies are used in C# programs. For example System.Console assembly is used to for printing and reading information to and from the output and input device. Similarly several assemblies are present in .NET platform which can be used for suitable purposes.* C# compiler will be informed regarding which assembly is used by writing the “using” line. Similarly .NET does not automatically load the required assembly during compilation process.* Therefore, in addition to specifying the namespaces that are used in *.cs file, VS .NET requires that a reference must be set to actual physical assembly.* Procedure to add assembly explicitly in VS .NET is to click on the option Add Reference in Project menu.

Running Vs Debugging* There are 2 ways to execute an application in VS .NET IDE.

1) Running (Debug| Start without Debugging)2) Debugging (Debug| Start Debugging)

* When a project is chosen to run, programmer is instructing VS .NET to ignore all breakpoints, and most important, to automatically prompt for a keystroke before terminating the current console window.* When an project is chosen to debug, which does not have any breakpoints set, the application terminates so quickly that the output will be not visible because there will be no prompt as such. So, when debug option is chosen then Console. Read ( ) line must be written as the end of the program.

Documenting your Source Code via XML* There is a facility in C# to convert the source code documentation into a corresponding XML file. When this is intended, first step is to make use of special comment syntax, the triple forward slash (///). After the triple slash, pgmr is free to use any well-formed XML elements, including the predefined set as shown below.

Predefined XML Documentation Element

Meaning

<c> Indicates that text within a description should be marked as code

<param> Describes a given parameter<paramref> Associates a given XML tag with a specific

parameter

12

Class View - VSapp

Vsapp Ex [class name]

Right click on this “Context sensitive” pop-up menu will appear

Page 13: C# Introduction Notes

Ex: using System;/// <summary>/// This is a simple Car the illustrates/// working with XML style documentation/// </summary>public class Car{

/// <summary> /// Do you have a sunroof? /// </summary> private bool hasSunroof = false; /// <summary> /// The ctor lets you set the sunroofedness. /// </summary> /// <param name="hasSunroof"> </param>

public Car(bool hasSunroof){

this.hasSunroof = hasSunroof; } …..

C# Preprocessor Directives* C# supports the use of various symbols that allow pgmr to interact with the compilation process.

C# Preprocessor Directives

Meaning

#define, #undef To define and un-define conditional compilation symbols

#if, #elif, #else, #endif

To conditionally skip sections of source code

#line To control line numbers emitted for errors & warnings

#error, #warning To issue errors & warnings for the current build#region, #endregion To explicitly mark sections of source code.

#region #endregion* A block of code can be written inside these directives. If done, the block of code may be hidden from view and identified by a friendly textual marker.

Ex: # region Not of much Importance public void swap ( ) { …. } # endregion

* By using these directives lengthy *.cs files are easily manageable. Code part written inside these directives can be hidden, if needed they can be brought to visibility by double clicking on it.

# define* #define defines a symbol, symbol can be defined, but cannot assign a value to a symbol. Using the symbol as the expression passed to the #if directive, the expression will evaluate to true.

* The #define directive must appear in the file before any instructions even before using line.

13

friendly textual marker

Page 14: C# Introduction Notes

* A symbol that is defined using #define does not conflict with a variable of the same name. That is, a variable name will not be passed to a preprocessor directive and a symbol will be evaluated by a preprocessor directive. The scope of a symbol created with #define is within the file in which it was defined.

Ex: # define PAR // PAR is a symbol without any value.

Conditional Code Compilation* #if is a category of conditional directive. Tests a symbol or symbols to see if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if & #endif.Ex:

* Confining to the above example if “#define A” line is removed from the program then output will be No, since the code inside #if & #endif will not be executed

#warning #error* These directive allow pgmr to instruct the C# compile to generate warning or error on the fly.Ex:

* If #warning directive is used warning will be generated but the application will be executed. If #error directive is used and preprocessed then application will not run.

14

#define Ausing System;class ex{ public static void Main() {#if (A) Console.WriteLine("Yes") ; #endif Console.WriteLine("No"); }}

Output: Yes No

#define Ausing System;class ex{ public static void Main() {#if (A) Console.WriteLine("Yes") ;#warning A has been defined#endif

#if (!A) Console.WriteLine("Yes");#error A has not been defined#endif } }

Page 15: C# Introduction Notes

System. Environment Class

* This class allows pgmr to obtain a no of details regarding the context of OS hosting .NET application using various static members.Ex:

using System;class ex{ public static void Main() { // OS version Console.WriteLine("Current OS: {0}", Environment.OSVersion);

//Current working directory Console.WriteLine("Current Directory: {0}", Environment.CurrentDirectory);

//Logical drives present in the system string[] drives = Environment.GetLogicalDrives( ); for(int i=0;i<drives.Length;i++) Console.WriteLine("Drive {0} : {1}", i,drives[i]);

//Version of .Net platform Console.WriteLine("Version of .NET : {0}", Environment.Version); }}

15