Você está na página 1de 39

Solutions to Chapter One Questions

1. What is .NET Framework? Ans. The .NET Framework is the foundation on which you can design, develop, and deploy applications. It is the core of the .NET infrastructure. It e ists as a layer !etween the .NET applications and the underlying operating system. The .NET Framework encapsulates much of the !asic functionality, such as de!ugging and security services, which was earlier !uilt into various programming languages. 2. What does .NET Framework consists of? Ans. The .NET Framework consists of We! forms, Windows forms, and console applications that pertain to the presentation layer of an application. We! forms are used in We!"!ased applications, whereas Windows Forms are used in Windows"!ased applications for providing an interactive user interface. In addition, you can create character"!ased console applications that can !e e ecuted from the command line. #esides these three components, the .NET Framework consists of two other components, the .NET Framework #ase $lasses and the $ommon %anguage &untime '$%&(. 3. Write a note on) a. *rogramming methodologies Ans. The +isual ,tudio .NET programming methodology allows for mi ed"language programming. This is esta!lished through a $ommon Type ,ystem '$T,( that is defined for all the languages that .NET Framework supports. -ll these languages compile into an intermediate language !efore they compile in native code. Therefore, the .NET developer has the independence to code one module of an application in one language and the other module of the same application in another language. b. *latform technologies Ans. The .NET Framework includes platform technologies like -./.NET, -,*.NET, and +#.NET. -./.NET allows .NET applications to communicate with a data!ase for retrieving, accessing, and updating data. -,*.NET is a framework for !uilding enterprise"class We! applications. +#.NET is an o!0ect"oriented language that provides features such as a!straction, encapsulation, and polymorphism. #y using these technologies, you can easily develop ro!ust We! applications, Windows applications, and 12% We! services. c. $ode e ecution Ans. The code e ecution process involves the conversion of Intermediate %anguage into native or $*3"specific code. The $%& is completely architecture"neutral. -ll the .NET languages get compiled into the I%. This intermediate language gets compiled !y 4ust"in"Time '4IT( compiler into the native machine code. -fter translating the I% into native code, the converted code is sent to the .NET runtime manager. The .NET runtime manager e ecutes the code. While e ecuting the code, a security check is performed to ensure that the code has the appropriate permissions for accessing the availa!le resources. 4. Which are the platform technologies supported !y .NET Framework? Ans. ,ome of the platform technologies supported !y .NET Framework are) -./.NET

5NIIT

$oordinator 6uide 7 #asics of .NET 8

-,*.NET +#.NET

5. %ist the advantages of .NET Framework. Ans. The .NET Framework offers the following advantages) Consistent programming model) The !ase classes of the .NET class li!rary provide standard functionality such as, input9output, remoting, thread management, string manipulation, user interface design, and security management. The -./.NET classes allow developers to access data in the form of 12%. 12% classes ena!le developers to read, write, manipulate, and transform 12% files. The -,*.NET classes support the development of We!"!ased applications and We! services. The Windows forms classes support the development of desktop"!ased applications. Together, the .NET class li!rary provides a common functionality to all .NET languages resulting in a consistent o!0ect model regardless of the programming language used !y the developer. Language independence) The .NET developer has the independence to code one module of an application in one language and the other module of the same application in another language. This language interopera!ility can help in code reuse, and improve the efficiency of the development process. Ease of application deployment) The .NET Framework manages the details of locating and loading the components re:uired !y an application, even if several versions of the same application e ist on the computer. The .NET Framework ensures that all the components on which the application depends are availa!le on the computer !efore the application !egins to run. +isual ,tudio ;<<= includes a new application deployment technology known as $lick/nce, which allows you to easily deploy a Windows forms application. $lick/nce ena!les you to create desktop applications that are deployed with a secure and system" controlled installation. Improved security) The .NET Framework provides several mechanisms for protecting resources and code from unauthori>ed users)

$ode -ccess ,ecurity '$-,( uses permissions to control the code accessing protected resources and operations. &ole"!ased security provides information needed to make decisions a!out user permissions. upport for !eb services) With the advent of .NET technology, We! services provide many !uilt"in #$% facilities that allow different applications from different sources to communicate with each other. We! services do not provide the user with a 63I. We! services instead share !usiness logic, data and processes through a programmatic interface across a network. Ease of creating dynamic !eb content) .ynamic We! content is easier to create with .NET. -,*. NET ;.< includes various features that ena!le you to easily develop We! applications having a consistent layout and appearance. "isual tudio .#E$) +isual ,tudio .NET is the 2icrosoft application and interface for programming in .NET. +isual ,tudio .NET provides all the programming advantages mentioned so far. This development environment has an e tensive set of ready"to use"controls, good de!ugging facilities, easy and simple programming features, and a vast set of .NET !ase classes. -ll these features ena!le you to develop high performance applications in a short period of time. %. What is !ackward compati!ility? Ans. #ackward compati!ility refers to the a!ility of a technology to work with its previous versions or with other earlier technologies. For e ample, the -ctive .irectory structure of Windows ;<<< is !ackward compati!le with Windows NT ?.=8 and @.<. ,imilarly, the .NET Framework supports !ackward compati!ility. For e ample, you can compile and run applications created in +isual #asic A.< in +isual ,tudio ;<<=.

; $oordinator 6uide 7 #asics of .NET

5NIIT

&. .oes .NET platform support !ackward compati!ility? E plain. Ans. The .NET platform supports !ackward compati!ility. It is possi!le for an application compiled in one version of the .NET Framework to run on a different version of the .NET Framework. For e ample, you can run applications developed in +isual ,tudio ;<<;9;<<? on +isual ,tudio ;<<=. In addition to the a!ove e ample, the .NET platform supports !ackward compati!ility in the following ways) The .NET Framework ;.< #$% supports !ackward compati!ility with the earlier versions. .NET supports $BB !ecause of !ackward compati!ility. To run a $BB code on .Net Framework, you need to include the following line at the !eginning of the code)
#using <mscorlib.dll>

+# applications can work on +#.NET and -,* applications can run on -,*.NET !ecause of !ackward compati!ility. Cou can easily reference $/2 components in.NET applications.

Solutions to Chapter Two Questions


1. With a neat diagram, e plain the .NET Framework architecture. Ans. The .NET Framework is the foundation on which you design, develop, and deploy applications. The .NET Framework consists of -,*.NET We! Forms, Windows Forms, and $onsole applications that pertain to the presentation layer of an application. We! Forms are used in We!"!ased applications, whereas Windows Forms are used in Windows"!ased applications for providing an interactive user interface. In addition, you can create character"!ased console applications that can !e e ecuted from the command line. #esides these three components, the .NET Framework consists of two other components, the .NET Framework #ase $lasses and the $%&. &efer to page 8@ of the ,6 for a diagram on the .NET Framework architecture. 2. %ist out the o!0ectives of the .NET Framework. Ans. The o!0ectives of .NET Framework are) To provide an o!0ect"oriented programming environment and to determine whether o!0ect code is stored and e ecuted locally, or e ecuted remotely. To provide a code"e ecution environment that minimi>es software deployment and versioning conflicts. To provide a code"e ecution environment that guarantees safe e ecution of code, including code created !y an unknown or semi"trusted third party. To provide a code"e ecution environment that eliminates the performance pro!lems of scripted or interpreted environments. To ensure consistency across varying types of applications, such as Windows"!ased applications and We!"!ased applications. To !uild all communication on industry standards to ensure that code !ased on the .NET Framework can integrate with any other code. 3. Dow is Windows *rogramming different from .NET *rogramming. Ans.

5NIIT

$oordinator 6uide 7 #asics of .NET ?

In Windows *rogramming, the application programs call Windows -*I function directly. The applications run in the Windows environment, that is, the operating system itself. These types of applications are called unmanaged or unsafe applications. In .NET *rogramming, the application calls the .NET #$% functions which communicate with the operating system. The applications run in .NET &untime environment. These types of applications are called managed or safe applications. The .NET &untime starts code e ecution, manages threads, provides services, and manages memory. 4. .efine the following) Ans. The $%& loads and e ecutes the code. $ode management is a fundamental principle of the runtime. It also provides services such as memory management, thread management, remoting, type safety, code security, and ro!ustness. Ans. The code that is developed with a language compiler that targets the $%& is called managed code. 2anaged code is designed to run on .Net environment. Ans. In the .NET framework, all the .NET languages get compiled into the 2,I% or simply the Intermediate %anguage 'I%(. The intermediate language is analogous to the !yte code of 4ava. The significant difference is that the !yte code is interpreted while the I% is compiled !y 4IT compilation to native machine code. Ans. The $T, is a standardi>ed set of !asic data types. This system provides a way to language interopera!ility. -n o!0ect implemented in one .NET supported language can call an o!0ect implemented in another .NET supported language. Ans. .NET #ase $lasses is a li!rary consisting of an e tensive set of functions for all services supported !y the Framework. This class li!rary provides classes that can !e used in the code to accomplish a range of common programming tasks such as string management, data collection, data!ase connectivity, and file access. Ans. -ssem!ly is the unit in which compiled managed code is stored. -n assem!ly contains I% and metadata. 2etadata gives details of the assem!ly, properties and methods stored in it, and security information. Ans. $ommon %anguage ,pecification '$%,( is a set of rules for !asic language features that have !een defined to enhance and ensure language interopera!ility. Ans. &eflection is the process of o!taining information a!out assem!lies and the types defined within them as metadata at runtime. 4IT compilation &eflection $%, -ssem!lies .NET #ase $lasses $T, Intermediate language 2anaged code $%&

@ $oordinator 6uide 7 #asics of .NET

5NIIT

Ans. 4IT compilation converts I% into its native machine code. The name 4IT is !ecause it compiles portion of code as and when re:uired at runtime. Ans. 2anifest is the area of the assem!ly where metadata is stored. Ans. -pplication domain is the !oundary that the $%& esta!lishes around o!0ects created within the same application. -pplication domain allows different code to run in the same process space. Ans. The gar!age collection feature relieves the programmer from the responsi!ility of freeing memory when no longer re:uired. The $%& calls the gar!age collector to handle memory efficiently. 5. What are the functionalities of $%&? 6ive the steps involved in the managed e ecution process. Ans. The $%& has the following functionalities) The $%& uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set runtime conte t !oundaries. The $%& automatically handles o!0ect layout and manages references to o!0ects, releasing them when they are no longer !eing used. -utomatic memory management eliminates memory leaks as well as some other common programming errors. The $%& makes it easy to design components and applications whose o!0ects interact across languages. /!0ects written in different languages can communicate with each other, and their !ehaviors can !e tightly integrated. The managed e ecution process includes the following steps) 8. $hoosing an appropriate language compiler. ;. $ompiling your code to 2,I% or simply I%) $ompiling translates your source code into I% and generates the re:uired metadata. ?. $ompiling I% to native code) -t e ecution time, a 4IT compiler translates the I% into the native machine code. .uring this compilation, the code must pass a verification process that e amines the I% and metadata to find out whether the code can !e determined to !e type safe. @. E ecuting code) The $%& provides the environment that ena!les e ecution as well as a variety of services that can !e used during e ecution. %. What are assem!lies? What are static and dynamic assem!lies? Ans. -ssem!ly is a !asic element of packaging in .NET. -n assem!ly consists of I% code, metadata that descri!es what is in the assem!ly, and any other files or information that the application needs to run, such as graphics and sound files. -ssem!lies can !e static or dynamic. ,tatic assem!lies can include .NET types 'interfaces and classes(, as well as re:uired resources for the assem!ly '!itmaps, 4*E6 files, resource files, and so on(. ,tatic assem!lies are stored on disk in *orta!le E ecuta!le '*E( files. .ynamic assem!lies are the ones that run directly from the memory, and are not saved on disk !efore e ecution. They can !e saved on the disk after they have !een e ecuted. &. Dow does the .NET e ecution environment with application domain differ from the traditional way of e ecution? 6ar!age collection -pplication domain 2anifest

5NIIT

$oordinator 6uide 7 #asics of .NET =

Ans. In the case of .NET Framework, application domains provide a secure and versatile unit of processing that the $%& can use to provide isolation !etween applications. ,everal application domains can !e run in a single process with the same level of isolation that would e ist as separate processes, !ut without incurring the additional overhead of making I*$ calls or switching !etween processes. Traditionally, the process !oundaries have !een used to isolate applications running on the same computer. Each application is loaded into a separate process, which isolates one application from another applications running on the same computer. The applications are isolated to provide process security. -s a result, the process cannot make direct calls to another process. Instead, I*$ techni:ues have to !e used to have communication !etween the processes. Each application is a separate process. '. What is the function of $T,? E plain the classification of types in $T, with the help of a diagram. Ans. The $T, defines how types are declared, used, and managed in the runtime. It is important for language interopera!ility. The $T, performs the following functions) Esta!lishes a common framework that ena!les cross"language integration, type safety, and high performance code e ecution. *rovides an o!0ect"oriented model. .efines rules that languages must follow, so that different languages can interact with each other.

$T, can !e classified into) +alue types &eference types

The following diagram illustrates type classification.

Type

+alue Types #uilt"In"+alue Types 3ser".efined +alue Types Enumerations ,elf .escri!ing Types $lass Types 3ser".efined $lasses

&eference Types *ointer Types -rrays #o ed +alue Types Interface Types

.elegates

Type Classification

+alue types directly store data in the varia!le. +alue types can !e !uilt"in type, user"defined types, or enumerations. &eference types store a reference to the dataEs memory address. &eference types can !e self"descri!ing types, pointer types, or interface types. ,elf"descri!ing types are further split into arrays and class types. The class types are user"defined classes, !o ed value types, and delegates. -ll types derive from the ,ystem./!0ect !ase type. (. Write a note on metadata.

A $oordinator 6uide 7 #asics of .NET

5NIIT

Ans. -n assem!ly stores all the information a!out itself. This information is called metadata and includes the name and version num!er of the assem!ly, security information, information a!out the dependencies, and a list of the files that constitute an assem!ly. 2etadata is the !inary information descri!ing the program. When we compile our code into a *E file, the metadata is inserted into one portion of the *E file, while the code is converted to I% and inserted into another portion of the *E file. Every type mem!er that are defined or referenced in a module is descri!ed within metadata. When code is e ecuted, the runtime loads metadata into memory and refers it to get information a!out the codeEs classes, mem!ers, inheritance, and so on. 2etadata allows .NET languages to descri!e themselves in a language"neutral manner. It gives re:uired information to the $%& to perform much of its functionalities. The presence of metadata makes the assem!ly self" descri!ing file. The $%& modules or components or other assem!lies which want to communicate with each other use this information stored in metadata to perform their tasks. 1). FIt is told that if we learn any one .NET language, then working with other .NET languages will !e easyG. Dow? E plain with an appropriate e ample. Ans. It can !e told that if you have learned any one .NET language, then working with other .NET languages will !e easy. This is !ecause all the .NET languages rely on the same managed classes of #$% for the same services. The same classes, methods, parameters, and types are used for all the system services regardless of any .NET language. %et us look at the following code that writes to and then reads from a file) // Program in C#
using System; using System.IO; static public void Main ! " Stream#riter s$%&ne$ Stream#riter 'temp.t(t') true!; string tempstring&'*i) t+is is ,opal'; s$%.#rite-ine tempstring!; s$%.Close !; Stream.eader sr%&ne$ Stream.eader 'temp.t(t'!; string /ilestring&sr%..ead0o1nd !; sr%.Close !; Console.#rite-ine /ilestring!; 2

// Program in 34.510
s+ared public sub Main ! dim s$% as Stream#riter&ne$ Stream#riter 'temp.t(t') true! dim tempstring as string& '*i) t+is is ,opal' s$%.#rite-ine tempstring! s$.Close ! dim sr% as Stream.eader&ne$ Stream.eader 'temp.t(t'! dim /ilestring as string&sr%..ead0o1nd ! sr%.Close ! Console.#rite-ine /ilestring! end sub

If we see, !oth versions of the a!ove program are nearly identical. The synta and use of ,tream&eader, ,treamWriter, and the $onsole class are identical, same methods, and identical parameters.

Solutions to Chapter Three Questions


1. %ist out the important features of $H. Ans. The features of $H are as follows)

5NIIT

$oordinator 6uide 7 #asics of .NET I

$H is an elegant, simple, type"safe, o!0ect"oriented language. $H has the capa!ility to !uild dura!le system"level components due to the following features)

Full $/29platform support for e isting code integration &o!ustness through gar!age collection and type safety ,ecurity provided through good design Full support of e tensi!le metadata concepts $H supports language interopera!ility and platform independence.

2. Write a program in $H to display JWelcome to the world of $ ,harpK. E plain the program. Ans. The $H program is as follows)
using System; namespace Console6pplication% " class #elcome " static void Main ! " System.Console.#rite-ine '#elcome to t+e $orld o/ C S+arp'!; Console..ead !; 2 2 2

The important points to !e noted in this program are) *ain met+od) *rogram e ecution !egins with the 2ain method. Input and output) The Write%ine function displays the string on the standard output device. Compilation and e,ecution) To compile the program, enter the following command)

csc #elcome.cs

To e ecute the program, enter the following command)


#elcome

3. E plain the general structure of a $H program. Ans. $H program can consist of one or more files. Each file can contain one or more namespaces. - namespace contains group of related types such as classes, structs, interfaces, enumerations, and delegates. Namespaces may !e nested. The following is the structure of a $H program that contains all of these elements)
using System; //7sing t+e System 5amespace namespace 5amespace% //8e/ining a namespace " class Class% //8e/ining a class " 2 struct Struct% // 8e/ining a structure " 2 inter/ace Inter/ace% //8e/ining an inter/ace " 2 delegate int 8elegate% !; enum 1num% //8e/ining an enumeration " 2 namespace 5amespace9 //8e/ining a namespace

L $oordinator 6uide 7 #asics of .NET

5NIIT

" 2 class Class9 //8e/ining a class " public static void Main string:; args! //Program e(ecution begins ///rom +ere " 2 2 2

4. Dow do namespaces and types in $H have uni:ue names? 6ive an e ample. Ans. Namespaces and types always have uni:ue names. If there are two classes with the same name !ut present in different namespaces, then !oth the o!0ects will have uni:ue fully :ualified names. $onsider the following code snippet)
namespace 64C " class Class% " 2 2 // 64C // 64C.Class%

namespace <=> // <=> " class Class% // <=>.Class% " 2 2

Dere the -#$.$lass8 and 1CM.$lass8 are two different types, even if the class name is same. 5. %ist out the difference !etween $H and $BB. Ans. The differences !etween $H and $BB are as follows. C# C# is a purely object-oriented language. The long data type is of 64 bits. C# supports ref and out parameters !hich are used instead of pointers in passing parameters by reference. "ointers are allo!ed in C# but only in the unsafe mode. C++ C++ supports object-oriented programming. The long data type is of 32 bits. C++ supports pointers in passing parameters by reference.

C# #s. C++

Solutions to Chapter Four Questions


1. Which are the two different categories of types in $H? Ans. In $H language, the types are divided into two categories) "alue types) +aria!les of the value types directly contain their data. With value types, the varia!les have their own copy of the data.

5NIIT

$oordinator 6uide 7 #asics of .NET N

-eference types) +aria!les of the reference types store address of their data. With reference types, it is possi!le for two varia!les to reference the same o!0ect. 2. What are varia!les? Dow many categories of varia!les are there in $H? .efine each. Ans. +aria!les represent storage locations. Every varia!le has a type that determines what kind of data can !e stored in the varia!le. There are seven categories of varia!les) tatic variables) - varia!le declared with the static modifier is called a static varia!le. There will !e only one copy of the varia!le, regardless of how many instances of class 'in which static varia!le e ists( are created. Instance variables) - varia!le declared without the static modifier is an instance varia!le. Array elements) The array is a container that has a list of storage locations for a specified type. The elements for a specified type of an array come into e istence when an array instance is created and e ists until there are no references to that array instance. "alue parameters) *arameters are arguments passed to the function. - parameter declared without a ref or out modifier is a value parameter. - value parameter comes into e istence when the function is invoked and is initiali>ed with the value of the argument passed. - value parameter e ists until the function returns. -eference parameters) - parameter declared with a ref modifier is a reference parameter. reference parameter does not create a new instance, it points to the same storage location of the parameter passed as an argument. .utput parameters) - parameter declared with an out modifier is an output parameter. The value of an out argument is not passed to the out parameter. Local variables) - local varia!le is declared within a !lock, like a for"statement, a switch"statement, or a using"statement. - local varia!le is not automatically initiali>ed and thus has no default value. 3. What is the importance of automatic memory management? E plain with e ample. Ans. 2anual memory management re:uires developers to manage the allocation and de"allocation of !locks of memory. 2anual memory management can !e !oth time consuming and difficult. In $H, automatic memory management is provided so that developers are freed from this manual task. -utomatic memory management increases code :uality and enhances developer productivity without negative impact on either e pressiveness or performance. $onsider the following e ample)
using System; public class Stac? " private 5ode /irst & null; public bool 1mpty " get " return /irst && null!; 2 2 public ob@ect Pop ! " i/ /irst && null! Console.#rite 'CanAt Pop /rom an empty Stac?.'!; else " ob@ect temp & /irst.3alue; /irst & /irst.5e(t; return temp; 2

8< $oordinator 6uide 7 #asics of .NET

5NIIT

2 public void Pus+ ob@ect o! " /irst & ne$ 5ode o) /irst!; 2 class 5ode " public 5ode 5e(t; public ob@ect 3alue; public 5ode ob@ect value!B t+is value) null! "2 public 5ode ob@ect value) 5ode ne(t! " 5e(t & ne(t; 3alue & value; 2 2 2

In the a!ove e ample, a ,tack class is implemented as a linked list of Node instances. These node instances are created in the *ush method and are deallocated when no longer in use. 4. Write a note on e pressions and operators in $H. Ans. -n e pression is a se:uence of operators and operands that specifies computation and assigns the result to a varia!le. E pressions are constructed from operands and operators. The operators of an e pression indicate which operations to perform. E amples for operators are B, ", O, 9, etc. E amples for operands are literals, varia!les, and e pressions. There are three kinds of operators) /nary operators) The unary operators operate on only one operand. For e ample, "" , BB. 0inary operators) The !inary operators operate on two operands. For e ample, B y.

$ernary operator) The ternary operator operates on three operands. For e ample, condition? truePe p) falsePe p. There is only one ternary operator, F?)G. The order of evaluation of operators in an e pression is determined !y the precedence and associa!ility of the operators. When an e pression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. For e ample, the e pression B y O > is evaluated as B 'y O >( !ecause the O operator has a higher precedence than the B operator. 5. What are empty statement and la!eled statements? Why are they used? Ans. -n empty statement 'Q( is used when there are no operations to perform. E ecution of an empty statement simply transfers control to the end point of the statement. For e ample, an empty statement can !e used when writing a while statement with a null !ody)
$+ile ; #aitCor6n1vent !!

-n empty statement can also !e used to declare a la!el 0ust !efore the closing JRK of a !lock)
void Cunc ! " ... i/ true! goto e(it; ... e(itB ; 2

- la!eled statement is prefi ed !y a la!el of a character string. %a!eled statements are permitted in !locks. - la!el is a name given !y the identifier. The scope of a la!el is the !lock in which the la!el is declared. If two la!els have the same name, you get a compile time error.

5NIIT

$oordinator 6uide 7 #asics of .NET 88

- la!el can !e referenced from goto statements within the scope of the la!el. %a!els and other identifiers can have the same name. $onsider the following e ample)
int Cunc int abc! " i/ abc >& D! goto abc; abc & Eabc; abcB return abc; 2

The a!ove e ample uses the name a!c as !oth a parameter and a la!el. %. What is an iterative statement? E plain foreach statement with e ample. Ans. Iteration statements repeatedly e ecute a !lock of statements. The num!er of iterations depends on the condition represented !y the !oolean e pression. The !lock of code will !e iterated until the condition is true. $onsider the following code)
using System; class 0estCoreac+ " static void Main ! " int:; array% & ne$ int:; "%)9)F)G)H2; /oreac+ int i in array%! Console.#rite-ine I3alue is "D2J) i!; 2 2

In the a!ove e ample, the foreach statement iterates through the elements of array8. &. %ist the different 0ump statements supported !y $H. Ans. The different 0ump statements supported !y $H are) !reak statement continue statement goto statement return statement throw statement

'. What are checked and unchecked statements? 6ive an e ample. Ans. The checked and unchecked statements are used to control the overflow checking for integer type arithmetic operations and conversions. The checked statement causes all e pressions in the checked !lock to !e evaluated in a checked conte t, and the unchecked statement causes all e pressions in the unchecked !lock to !e evaluated in an unchecked conte t. $hecked allows you to raise an e ception whenever stack overflow 'or underflow( occurs due to type conversion issues. 3nchecked will allow you to ignore these e ceptions when the $H pro0ect is set to raise these types of e ceptions. $onsider the following e ample)
static void Main ! " int ( & IntF9.Ma(3alue;

8; $oordinator 6uide 7 #asics of .NET

5NIIT

Console.#rite-ine ( K %!; // Over/lo$ c+ec?ed " Console.#rite-ine ( K %!; // 1(ception 2 unc+ec?ed " Console.#rite-ine ( K %!; // Over/lo$ 2 2

In the a!ove e ample, the checked keyword allows you to report the overflow at runtime. (. 6ive an e ample of lock and using statements. Ans. E ample of lock statement)
static void Main ! " 6 a & ...; loc? a! " a.P & a.P K %; 2 2

In the a!ove code snippet, a !lock of code o!tains a mutual"e clusion lock. E ample of using statement)
static void Main ! " using .esource r & ne$ .esource !! " r.Cunc !; 2 2

In the a!ove code snippet, resources are o!tained with the using statement. 1). Dow are structures different from classes in $H? Ans. ,tructures are value types and classes are reference type. - varia!le of a structure type directly contains the data of the structure, whereas a varia!le of a class type contains a reference to the o!0ect. Cou can inherit classes !ut you cannot inherit structures. 11. What are interfaces? 6ive an e ample. Ans. Interfaces are used to define a contractQ a class or struct that implements the interface must o!ey to this contract. Interfaces can contain methods, properties, inde ers, and events as mem!ers. They cannot contain constants, fields 'private data mem!ers(, constructors, and destructors, or any type of static mem!er. -ll the mem!ers of an interface are pu!lic !y definition. $onsider the following e ample)
inter/ace I1(ample " string t+is:int inde(; " get; set; 2 event 1vent*andler 1; void Cunc int value!; string P " get; set; 2 2 public delegate void 1vent*andler ob@ect sender) 1vent6rgs e!;

The a!ove e ample shows an interface that contains an inde er, an event E, a method Func, and a property *.

5NIIT

$oordinator 6uide 7 #asics of .NET 8?

12. What is a delegate? What is the use of it? 6ive an e ample. .elegates are o!0ects that you use to call the methods of other o!0ects. .elegates are said to !e o!0ect"oriented function pointers since they allow a function to !e invoked indirectly !y using a reference to the function. - delegate declaration defines a class that is derived from the class ,ystem..elegate. - delegate instance encapsulates one or more methods, each of which is referred to as a calla!le entity. For instance methods, a calla!le entity consists of an instance and a method on that instance. For static methods, a calla!le entity consists of 0ust a method. 6iven a delegate instance and an appropriate set of arguments, one can invoke all instance methods of that delegate with that set of arguments. $onsider the following e ample of a delegate)
class 0est " static void C ! " System.Console.#rite-ine '0est.C'!; 2 static void Main ! " Simple8elegate dele & ne$ Simple8elegate C!; dele !; 2 2

The a!ove e ample creates a ,imple.elegate instance, dele, and then immediately calls it. This program displays Test.F. 13. Write a program to demonstrate the usage of enums in $H. Ans. The following program illustrates the use of enums.
enum Color " .ed) 4lue) ,reen 2 class S+ape " public void Cill Color color! " s$itc+ color! " case Color..edB Console.#rite-ine I.18J!; brea?; case Color.4lueB Console.#rite-ine I4-71J!; brea?; case Color.,reenB Console.#rite-ine I,.115J!; brea?; de/aultB brea?; 2 Console..ead !; 2 2

8@ $oordinator 6uide 7 #asics of .NET

5NIIT

The a!ove program shows a color enum and a method that uses this enum. 14. Write a note on namespaces in $H. Ans. $H programs are organi>ed !y using namespaces. Namespaces are used !oth as an FinternalG organi>ation system for a program, and as an Fe ternalG organi>ation system. This is a way of writing program elements that are e posed to other programs. - namespace declaration consists of the keyword namespace, followed !y a namespace name and !ody)
namespace 5amespace5ame " ... // namespace body 2

$lasses actually contain data and Namespaces are used to logically arrange classes. Namespaces can also contain many other Namespaces and classes. $H classes are organi>ed !y using namespaces. Namespaces provide a way to group classes !y providing an e tra level of naming !eyond the class name. Namespaces are implicitly pu!lic and the declaration of a namespace does not include any access modifiers. The identifier or name of a namespace may !e a single identifier or a se:uence of identifiers separated !y J.K tokens. The latter form permits a program to define a nested namespace. $onsider the following code snippet)
namespace 1(ample.5amespace% " public class 5m1( " public string 8isplay ! " return '5amespace e(ample'; 2 2 2

Namespaces are hierarchical, and the name E ample.Namespace8 is an easier and convenient way for defining a namespace named E ample that contains a namespace named Namespace8, as in)
namespace 1(ample " namespace 5amespace% " 2 2

15. What is the use of attri!utes in $H programs? Ans. $H is an imperative language, !ut like all imperative languages it does have some declarative elements. For e ample, the accessi!ility of a method in a class is specified !y declaring it pu!lic, protected, internal, protected internal, or private. $H generali>es this capa!ility, so that programmers can invent new kinds of declarative information, attach this declarative information to various program entities, and retrieve this declarative information at runtime. *rograms specify this additional declarative information !y defining and using attri!utes.

olutions to C+apter 1ive 2uestions


1. Write a note on classes in $H.

5NIIT

$oordinator 6uide 7 #asics of .NET 8=

Ans. - class is a collection of varia!les and methods. The class defines all the common properties of the different o!0ects that !elong to it. $lass declarations are reference types. - class can inherit from another class and can implement interfaces. $lass mem!ers can include constants, fields, methods, properties, events, inde ers, operators, instance constructors, destructors, static constructors, and nested type declarations. Each mem!er has an associated accessi!ility, which controls the portion of the program code that is a!le to access the mem!er. There are five forms of accessi!ility. These are as follows) *u!lic, which is selected !y including a pu!lic modifier in the mem!er declaration. The intuitive meaning of pu!lic is Jaccess not limitedK. *rotected internal 'meaning protected or internal(, which is selected !y including !oth a protected and an internal modifier in the mem!er declaration. The intuitive meaning of protected internal is Jaccess limited to this program or types derived from the containing classK. *rotected, which is selected !y including a protected modifier in the mem!er declaration. The intuitive meaning of protected is Jaccess limited to the containing class or types derived from the containing classK. Internal, which is selected !y including an internal modifier in the mem!er declaration. The intuitive meaning of internal is Jaccess limited to the programK. *rivate, which is selected !y including a private modifier in the mem!er declaration. The intuitive meaning of private is Jaccess limited to the containing typeK. 2. What are constant mem!ers? 6ive an e ample. Ans. - constant is a class mem!er that represents a constant value. $onstant mem!ers are initiali>ed at the time of their declaration. $onsider the following e ample)
class Constants " public const int 6 & %; public const int 4 & 6 K %; 2

The a!ove e ample shows a class named $onstants that has two pu!lic constants. 3. 6ive an e ample of field mem!er. Ans. $onsider the following code, which displays a class and its field mem!ers)
class Color " internal us+ort redPart; internal us+ort bluePart; internal us+ort greenPart; public Color us+ort red) us+ort blue) us+ort green! " redPart & red; bluePart & blue; greenPart & green; 2 public static readonly Color .ed & ne$ Color D(CC) D) D!; public static readonly Color 4lue & ne$ Color D) D(CC) D!; public static readonly Color ,reen & ne$ Color D) D) D(CC!; public static readonly Color #+ite & ne$ Color D(CC) D(CC) D(CC!; 2

In the a!ove e ample, the $olor class has the fields) red*art, !lue*art, green*art, &ed, #lue, 6reen, and White. 4. With appropriate e amples, e plain parameter passing in $H.

8A $oordinator 6uide 7 #asics of .NET

5NIIT

Ans. *arameters can !e passed !y value or !y reference. These are e plained as follows) 3assing by value) The parameter modifiers ErefE and EoutE relate to how the parameter is passed into the method. #y default, parameters are passed !y value. In this case, when the method is called, the value given is copied to the varia!le specified in the method declaration. The following e ample illustrates this pointQ note that the change made to varia!le b in the !ody of the EchangeE method does not result in a change to the varia!le a used to invoke the method. $onsider the following code snippet)
public static void Main ! " int a & D; c+ange a!; Console.#rite-ine a!; //-ine 9 2 public static void c+ange int b! " b & H; Console.#rite-ine b!; //-ine % 2 In the a!ove e ample, the value of a is initiali>ed to <. When the change method is called, the value of a is changed to =. Therefore, %ine8 displays =. Dowever, the parameter a is passed !y value. Therefore the original value of a does not change. Therefore, %ine; would display <.

3assing by reference) In $H, you can pass varia!les into methods E!y referenceE. When a varia!le is passed !y reference, the ErefE modifier must !e used !oth in the method definition argument list and the method invocation. $onsider the following e ample)
public static void Main ! " int a & D; c+ange re/ a!; Console.#rite-ine a!; //-ine9 2 public static void c+ange re/ int b! " b & H; Console.#rite-ine b!; //-ine% 2

In the a!ove e ample, the value of a is initiali>ed to <. When the change method is called, the value of a is changed to =. Therefore, %ine8 displays =. Dere, the parameter a is passed !y reference. Therefore the original value of a changes. Therefore, %ine; would display =. 5. What is the use of property mem!er in a class? Ans. - property is a mem!er that provides access to a characteristic of an o!0ect or a class. E amples of properties include the length of a string, the si>e of a font, the caption of a Window, the name of a customer, and so on. *roperties are a natural e tension of fields. #oth are named mem!ers with associated types, and the synta for accessing fields and properties is the same. Dowever, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the !lock of statements to !e e ecuted when their values are read or written. %. What are events? 6ive an e ample to demonstrate its usage. Ans. -n event is a set of actions that is triggered to call a function or to start an operation. - class defines an event !y providing an event declaration and an optional set of event accessors. The declaration resem!les a field declaration, with an added event keyword. The type of this declaration must !e a delegate type.

5NIIT

$oordinator 6uide 7 #asics of .NET 8I

$onsider the following e ample)


void 4utton%LClic? ob@ect sender) 1vent6rgs e! " Message4o(.S+o$ '4utton% $as clic?edM'!; 2

In the a!ove e ample, a click event is raised when #utton8 is clicked. &. With an e ample, e plain inde ers. Ans. -n inde er ena!les an o!0ect to !e inde ed in the same way as an array. Whereas properties ena!le field"like access, inde ers ena!le array"like access. Inde er declarations are similar to property declarations, with the main differences !eing that inde ers are nameless and that inde ers include inde ing parameters. The inde ing parameters are provided !etween s:uare !rackets. $onsider the following e ample)
using System; public class Stac? " private 5ode ,et5ode int inde(! " 5ode temp & /irst; $+ile inde( > D! " temp & temp.5e(t; inde(EE; 2 return temp; 2 public ob@ect t+is:int inde(; " get " i/ M3alidInde( inde(!! t+ro$ ne$ 1(ception 'Inde( out o/ range.'!; else return ,et5ode inde(!.3alue; 2 set " i/ M3alidInde( inde(!! t+ro$ ne$ 1(ception 'Inde( out o/ range.'!; else ,et5ode inde(!.3alue & value; 2 2 ... 2 class 0est " static void Main ! " Stac? s & ne$ Stac? !; s.Pus+ %!; s.Pus+ 9!; s.Pus+ F!; s:D; & FF; // C+anges t+e top item /rom F to FF s:%; & 99; // C+anges t+e middle item /rom 9 to 99 s:9; & %%; // C+anges t+e bottom item /rom % to %% 2 2

The a!ove e ample shows an inde er for the ,tack class.

8L $oordinator 6uide 7 #asics of .NET

5NIIT

'. E plain each of the following with an e ample) a. Instance constructors Ans. -n instance constructor is a mem!er that implements the actions re:uired to initiali>e an instance of a class. $onsider the following e ample)
using System; class Point " public double () y; // Instance constructor public Point ! " t+is.( & D; t+is.y & D; 2 //ParameteriNed Instance constructor public Point double () double y! " t+is.( & (; t+is.y & y; 2 public static double 8istance Point a) Point b! " double (di// & a.( E b.(; double ydi// & a.y E b.y; return Mat+.SOrt (di// P (di// K ydi// P ydi//!; 2 public override string 0oString ! " return string.Cormat ' "D2) "%2!') () y!; 2 2 class 0est " static void Main ! " Point a & ne$ Point !; Point b & ne$ Point F) G!; double d & Point.8istance a) b!; Console.#rite-ine '8istance /rom "D2 to "%2 is "92') a) b) d!; 2 2

The a!ove e ample shows a *oint class provides two pu!lic instance constructors, one of which takes no arguments, while the other takes two arguments. b. .estructor Ans. - destructor is a mem!er that implements the actions re:uired to destroy an instance of a class. .estructors cannot have parameters, they cannot have accessi!ility modifiers, and they cannot !e called e plicitly. The destructor of an instance is called automatically during gar!age collection. $onsider the e ample)
using System; class Point

5NIIT

$oordinator 6uide 7 #asics of .NET 8N

" public double () y; public Point double () double y! " t+is.( & (; t+is.y & y; 2 QPoint ! " Console.#rite-ine '8estructed "D2') t+is!; 2 public override string 0oString ! " return string.Cormat ' "D2) "%2!') () y!; 2 2

The a!ove e ample shows a *oint class with a destructor. c. ,tatic constructor Ans. - static constructor is a mem!er that implements the actions re:uired to initiali>e a class. ,tatic constructors cannot have parameters, they cannot have accessi!ility modifiers, and they cannot !e called e plicitly. The static constructor for a class is called automatically. $onsider the following code snippet)
class 1mployee " private static 8ataSet ds; static 1mployee ! " ds & ne$ 8ataSet ...!; 2 public string 5ame; public decimal Salary; ... 2

The a!ove e ample shows an Employee class with a static constructor that initiali>es a static field. (. Dow does $H support inheritance? Ans. $H classes support inheritance !y using the FB4 operator. $onsider the following e ample)
using System; class 6 " public void C ! " Console.#rite-ine 'Inside 6.C'!; 2 2 class 4B 6 " public void , ! " Console.#rite-ine 'Inside 4.,'!; 2 2 class 0est " static void Main ! " 4 b & ne$ 4 !; b.C !; // In+erited /rom 6

;< $oordinator 6uide 7 #asics of .NET

5NIIT

b., !; 6 a & b; a.C !; 2 2

// Introduced in 4 // 0reat a 4 as an 6

The output will !e) Inside -.F Inside #.6 Inside -.F The a!ove program shows a class # that derives from -. The class # inherits -Es F method, and introduces a 6 method of its own. 1). What is method overloading? 6ive an e ample. Ans. 2ethod overloading refers to the methods with the same name !ut different signatures doing different tasks. $onsider the following e ample)
using System; class Polymorp+ism1( " public static int add int a) int b! " int sum&aKb; Console.#rite-ine sum!; 2 public static int add int a) int b) int c! " int sum&aKbKc; Console.#rite-ine sum!; 2 static void main ! " add F)G!; add F)G)H!; add H)R!; 2 2

In the a!ove e ample, the add function is overloaded as the two add functions have different signatures. The output of the a!ove program is) I 8; 88 11. What is operator overloading? 6ive an e ample. Ans. /perator overloading refers to loading an operator to perform different operations on different data types on different conte ts. To overload an operator in a class, one defines a method !y using the EoperatorE keyword. The following program uses operator overloading to create a comple num!er class $omple -dd that defines comple addition. The program displays the imaginary and the real parts of the num!ers and the addition result using an override of the To,tring method.
// comple(6dd.cs

5NIIT

$oordinator 6uide 7 #asics of .NET ;8

using System; public struct Comple(6dd " public int r; public int img; public Comple( int r) int img! " t+is.r & r; t+is.img & img; 2 // 8eclare $+ic+ operator to overload public static Comple(6dd operator K Comple(6dd c%) Comple(6dd c9! " return ne$ Comple(6dd c%.r K c9.r) c%.img K c9.img!; 2 // Override t+e 0oString met+od to display a comple( number in a reOuired /ormatB public override string 0oString ! " return String.Cormat '"D2 K "%2i') r) img!!; 2 public static void Main ! " Comple(6dd var% & ne$ Comple(6dd H)F!; Comple( var9 & ne$ Comple( R)9!; // 6dd t$o Comple( ob@ects var% and var9! t+roug+ t+e // overloaded plus operatorB Comple(6dd total & var% K var9; // Print t+e numbers and t+e sum using t+e overridden 0oString met+odB Console.#rite-ine 'Cirst comple( numberB "D2')var%!; Console.#rite-ine 'Second comple( numberB "D2')var9!; Console.#rite-ine '0+e sum o/ t+e t$o numbersB "D2')total!; 2 2

.utput First comple num!er) = B ?i ,econd comple num!er) A B ;i The sum of the two num!ers) 88 B =i

Solutions to Chapter Six Questions


1. What is a preprocessor? E plain the purpose of the following directives) Hif Helse Helif Hendif Hdefine Hundef Hwarning Herror Hline

Ans.

;; $oordinator 6uide 7 #asics of .NET

5NIIT

- preprocessor manipulates the source code. It !reaks up the source code into modules. *reprocessor directives instruct the preprocessor to perform specific tasks. ,ome of the preprocessor directives are e plained !elow. 5if) It !egins a conditional directive for testing a sym!ol, to see if they evaluate to true. If true, the compiler evaluates all the code !etween the Hif and the ne t corresponding directive. Helse) It evaluates if none of the e pressions in the preceding Hif or Helif directives evaluate to true. 5elif) It evaluates if neither the preceding Hif nor any preceding Helif directive e pressions evaluate to true. 5endif) It specifies the end of an Hif directive. 5define) It defines a sym!ol, which can !e passed to the Hif directive to evaluate the e pression as true. $onsider the following code, which illustrates the use of Hif, Helse, Helif, Hendif, and Hdefine)
#de/ine 8147, #de/ine 3CL3R using System; public class I/Class " public static void Main ! " #i/ 8147, SS M3CL3R! Console.#rite-ine '8147, #eli/ M8147, SS 3CL3R! Console.#rite-ine '3CL3R #eli/ 8147, SS 3CL3R! Console.#rite-ine '8147, #else Console.#rite-ine '8147, #endi/ 2 2 +as been de/ined'!; +as been de/ined'!; and 3CL3R +as been de/ined'!; and 3CL3R +as not been de/ined'!;

.utput .E#36 and +$P+A has !een defined. Hundef) It undefines a sym!ol. $onsider the following code)
#unde/ 8147, using System; public class 0est " public static void Main ! " #i/ 8147, Console.#rite-ine '8147, +as been de/ined'!; #else Console.#rite-ine '8147, +as not been de/ined'!; #endi/ 2 2

.utput .E#36 has not !een defined. 56arning) It generates a %evel 8 warning from a specific location in the code. $onsider the following code snippet)
#de/ine 8147, public class 0est " public static void Main ! " #i/ 8147,

5NIIT

$oordinator 6uide 7 #asics of .NET ;?

#$arning 8147, de/ined #endi/ 2 2

5error) It generates an error from a specific location in the code. $onsider the following code snippet)
#de/ine 8147, public class 0est " public static void Main ! " #i/ 8147, #error 8147, de/ined #endi/ 2 2

5line) It changes the compilerEs line num!er and the file name. $onsider the following code snippet)
public class 0est " public static void Main ! " #line %DD int i; // error or $arning $ill beB ICSD%RT on line %DDJ #line %D c+ar c; // error or $arning $ill beB ICSD%RT on line %DJ 2 2

2. What is an e ception? Dow are e ceptions handled in $H? Ans. -n e ception is any error condition or une pected !ehavior encountered !y a program in e ecution. E ceptions can !e raised !ecause of) Fault in the code or in shared li!rary. 3navaila!ility of operating system resources. 3ne pected conditions encountered !y the $%& encounters.

E ceptions are handled !y a try statement. When an e ception occurs, the system searches for the nearest catch !lock that can handle the e ception. /nce a matching catch !lock is found, the control is transferred to the first statement of the catch !lock and the catch !lock e ecutes. If no matching catch !lock or finally !lock is found, then the e ecution of the thread is terminated. Note) If the application does not handle these e ceptions, then the application terminates 'default !ehavior(. 3. What is an unsafe code? E plain. Ans. 3nsafe code refers to the code that is processed with low security levels. There are situations where access to pointer types !ecomes a necessity. For e ample, interfacing with the underlying operating system, accessing a memory"mapped device, or implementing a time"critical algorithm may not !e possi!le without access to pointers. To address this need, $H provides the a!ility to write unsafe code. In unsafe code, it is possi!le to declare and operate on pointers, to perform conversions !etween pointers and integral types, to take the address of varia!les, and so forth. In a sense, it is like writing $ code within a $H program. 3nsafe code must !e clearly marked with the modifier unsafe, so developers cannot possi!ly use unsafe features accidentally. When $%& finds this unsafe modifier, the e ecution engine works to ensure that the unsafe code cannot !e e ecuted in an untrusted environment.

;@ $oordinator 6uide 7 #asics of .NET

5NIIT

4. What is threading? %ist out the advantages and disadvantages of multiple threads. Ans. Threads are the !asic unit to which an operating system allocates processor time, and more than one thread can run inside that process. Each thread maintains e ception handlers, a scheduling priority, and a set of structures the system uses to save the thread conte t until it is scheduled. The thread conte t includes all of the information the thread needs to resume e ecution, including the set of $*3 registers and stack, in the address space of the threadEs host process. 2ultithreading offers the following advantages) Improved responsiveness) If the application is performing operations that take a perceiva!ly long time to complete, these operations can !e put into a separate thread which will allow the application to continue to !e responsive to the user. 1aster application) 2ultiple threads can lead to improved application performance. For e ample, if there are a num!er of calculations to !e performed, then there the application can !e made faster !y performing multiple operations at the same time. 3rioriti7ation) Threads can !e assigned a priority which would allow higher priority tasks to take precedence over lower priority tasks. 3rogramming and debugging is more comple,) With multithreaded applications the programmer must ensure deadlock avoidance. $+reads add over+ead to t+e system) In order for the operating system to track a large num!er of threads it is going to consume processor time. If there are too many threads then each thread may not !e given enough time to e ecute during its time slice.

2ultithreading has the following disadvantages)

5. Write a note on li!rary !ase classes. Ans. The .NET Framework !ase classes include classes, interfaces, and value types that provide access to system functionality. To facilitate interopera!ility !etween languages, the .NET Framework !ase classes are $%, compliant and therefore can !e used from any programming language. The .NET Framework li!rary !ase classes are the foundation on which .NET applications, components, and controls are !uilt. These also include types that perform the following functions) &epresent !ase data types and e ceptions Encapsulate data structures *erform I9/ operations -ccess information of data types *erform .NET Framework security checks *rovide data access, 63I, and We! services

%. What is the role of ,ystem./!0ect, ,ystem.,tring, ,ystem.-rray and ,ystem.$ollections $lasses? Ans. The roles of the various classes and namespaces are as follows) The ,ystem./!0ect class provides classes and methods that allow you to !uild generic routines, provides Type ,ystem 3nification, and ena!les working with groups collections. The ,ystem.,tring class provides methods that allow you to perform various string operations. The ,ystem.-rray class provides methods for creating, traversing, manipulating, sorting, and searching arrays. The ,ystem.$ollections namespace contains interfaces and classes that allow you to define various collections of o!0ects, such as lists, :ueues, !it arrays, hash ta!les, and dictionaries.

5NIIT

$oordinator 6uide 7 #asics of .NET ;=

&. What are the different methods supported !y ,ystem./!0ect class? 6ive an e ample for each. Ans. The methods are) E8uals) This method of the o!0ect class provides a default implementation that compares two reference type o!0ects for reference e:uality. The following code snippet illustrates the use of the E:uals method)
public static void Main ! " string str%& IMar?J; string str9& I6damJ; strF& IMar?J; Console.#rite-ine Ob@ect.1Ouals str%)str9!!; //8isplays Calse Console.#rite-ine Ob@ect.1Ouals str%)strF!!; //8isplays 0rue 2

-eferenceE8uals) This method compares o!0ect instances. The following code snippet illustrates the use of the &eferenceE:uals method)
public static void Main ! " ob@ect ob@%& null; ob@ect ob@9& null; Console.#rite-ine Ob@ect..e/erence1Ouals ob@%)ob@9!!; 0rue 2

//8isplays

$o tring) This method returns a string representation of a type. The following code snippet illustrates the use of the To,tring method)
public class 1(ample " void StrConvert ! " Ob@ect ob@& ne$ Ob@ect !; Console.#rite-ine ob@.0oString !!; //8isplays System.Ob@ect 2 2

9et$ype) This method returns a Type o!0ect, descri!ing the o!0ect it was called on. The following code snippet illustrates the use of the 6etType method)
public static void Main ! " Class% ob@& ne$ Class% !; Console.#rite-ine ob@.,et0ype !!; //8isplays Class% 2

9et:as+Code) This method makes any o!0ect usa!le in a hash ta!le or any hashing algorithm. The following code snippet illustrates the use of the 6etDash$ode method)
public struct IntF9 " public int val; public override int ,et*as+Code !

;A $oordinator 6uide 7 #asics of .NET

5NIIT

" return val; //.eturns an integer value 2 2

*ember6iseClone) This method is used to create a !itwise copy of the type. The following code snippet illustrates the use of the 2em!erwise$lone method)
public static void Main ! " Class% ob@%& ne$ Class% !; ob@%.name& IStep+enJ; Class% ob@9 & Class%!ob@%.Member$iseClone; 2

1inali7e) This method is used as a destructor. The Finali>e destructor is called after the last reference to an o!0ect is released from the memory. The .NET Framework automatically runs the Finali>e destructor to destroy o!0ects in the memory. The following code snippet illustrates how to override the Finali>e method)
QOb@ect !;

'. What is !o ing and un!o ing? E plain with an e ample. Ans. #o ing refers to the conversion of value types to o!0ect types. $onsider the following code snippet)
public static void Main ! " int var& 9%; ob@ect ob@&var; //4o(ing 2

In the memory, var and o!0 are represented in the following manner. tac; :eap
21

var

o!0
int 21 $epresentation of %ar and obj in &emory

3n!o ing refers to the conversion of o!0ect types to value types. $onsider the following code snippet)
public static void Main ! " int var& 9%; ob@ect ob@&var; //4o(ing int var9& 2 int!ob@;

In the memory, var, o!0, and var; are represented in the following manner.

5NIIT

$oordinator 6uide 7 #asics of .NET ;I

tac;

:eap
21

var

o!0
int 21

var;
21 $epresentation of %ar obj and %ar2 in &emory

(. Write a program to replace all FrG !y F&G in the string Jrose is a roseK. Ans. This program is given !elow)
using System; namespace Console6pplication% " class C+ange " static void Main ! " string errString & 'rose is a rose'; string correctString & errString..eplace 'r') '.'!; Console.#rite-ine correctString!; Console..ead-ine !; 2 2 2

1). Write a note on the following) a. ,ingle"dimensional arrays Ans. ,ingle"dimension array is defined as an array having only one dimension. We can declare a single"dimension array of five integers in the following way)
int:; arr & ne$ int :H;;

This array contains the elements from arrS<T to arrS@T. The new operator is used to create the array and initiali>e the array elements to their default values. In this case, all the array elements are initiali>ed to >ero. -n array that stores string elements can !e declared in the same way. For e ample)
string:; myString6rray & ne$ string:R;; b. Multidimensional arrays

Ans. 2ultidimensional array is defined as an array having more than one dimension. For e ample, the following declaration creates a two"dimensional array of four rows and two columns)
int:); arr & ne$ int:G)9;;

The following code creates an array of three dimensions, @, ;, and ?, as shown !elow)

;L $oordinator 6uide 7 #asics of .NET

5NIIT

int:)); arr & ne$ int :G)9)F;;

c. 4agged arrays Ans. - 0agged array is an array whose elements are arrays. The elements of a 0agged array can !e of different dimensions. The following is a declaration of an array that has three elements, each of which is a single"dimensional array of integers)
int:;:; myUagged6rr & ne$ int:F;:;;

#efore we can use my4agged-rr, its elements must !e initiali>ed. We can initiali>e the elements like)
myUagged6rr :D; & ne$ int:H;; myUagged6rr :%; & ne$ int:G;; myUagged6rr :9; & ne$ int:9;;

Each of the elements is a single"dimensional array of integers. The first element is an array of = integers, the second is an array of @ integers, and the third is an array of ; integers. It is also possi!le to use initiali>ers to fill the array elements with values, in which case we do not need the array si>e. For e ample)
myUagged6rr :D; & ne$ int:; "%)F)G)V)W2; myUagged6rr :%; & ne$ int:; "D)9)W)R2; myUagged6rr :9; & ne$ int:; "%T)992;

- 0agged array can !e initiali>ed in the following manner as well)


int:;:; myUagged6rr & ne$ int :;:; " ne$ int:; "%)F)H)V)W2) ne$ int:; "D)9)G)R2) ne$ int:; "%%)992 2;

d. *assing arrays !y using ref and out Ans. The ref and out parameters allow you to retain the change in the value of a varia!le when control passes !ack to the calling procedure. Without these keywords, the varia!le would not retain the modified value once the control passes !ack to the calling procedure. - ref parameter of an array type must !e assigned !y the caller. Therefore, there is no need to !e definitely assigned !y the callee. - ref parameter of an array type may !e altered as a result of the call. For e ample, the array can !e assigned the null value or can !e initiali>ed to a different array. For e ample)
public static void MyMet+od re/ int:; arr! " arr & ne$ int:%D;; // arr initialiNed to a di//erent array 2

-n out parameter of an array type must !e assigned !efore it is usedQ that is, it must !e assigned !y the callee. For e ample)
public static void MyMet+od out int:; arr! " arr & ne$ int:%D;; // de/inite assignment o/ arr 2

11. What is the use of ,ystem.$ollections namespace? Ans.

5NIIT

$oordinator 6uide 7 #asics of .NET ;N

The ,ystem.$ollections namespace contains interfaces and classes that are used to define various collections of o!0ects, such as lists, :ueues, !it arrays, hashta!les and dictionaries.

Solutions to Chapter Seven Questions


1. 6ive the overall concept of -./.NET with the help of figures. Ans. -ctive1 .ata /!0ects for the .NET Framework '-./.NET( is a set of classes that provide data access services to the .NET programmer. -./.NET provides a rich set of components for creating distri!uted, data"sharing applications. It is an integral part of the .NET Framework, providing access to relational data!ase, 12%, and application data. -./.NET supports a variety of development needs, including the creation of front end data!ase clients and middle tier !usiness o!0ects used !y applications, tools, languages, or Internet !rowsers. -./.NET provides consistent access to data sources such as 2icrosoft ,U% ,erver, or data sources e posed via /%E .# and 12%. .ata sharing applications can use -./.NET to connect to these data sources and retrieve, manipulate, and update data. The data residing in a data!ase is retrieved through data provider. .ifferent components of the data provider retrieve data from the data!ase, provide the data to the +isual #asic .NET application, and update the data!ase with the changes made in the application. -n application can access data either through a dataset or through a .ata&eader o!0ect) /sing a dataset) In this case, the data is cached in a dataset and the application accesses the data from the dataset. /sing a data reader) In this method, a .ata&eader o!0ect, which is a component of the data provider, uses the $onnection o!0ect to connect to the data!ase, uses the $ommand o!0ect to retrieve data, and provides data to the application in a read"only and forward"only mode.

&efer to pages 8;<"8;? of the ,6 for diagrams on the -./.NET architecture. 2. E plain in detail the -./.NET architecture. Ans. The -./.NET components have !een designed for easy access and manipulation of data. There are two central components of -./.NET, .ata,et and .NET .ata *rovider. The -./.NET .ata,et is the core component of the disconnected architecture of -./.NET. The .ata,et is e plicitly designed for data access independent of any data source. It can !e used with multiple and different data sources, used with 12% data, or used to manage data local to the application. The .ata,et contains a collection of one or more .ataTa!le o!0ects. The other core element of the -./.NET architecture is the .NET .ata *rovider, whose components '$onnection, $ommand, .ata&eader, and .ata-dapter( are e plicitly designed for data manipulation. The $onnection o!0ect provides connectivity to a data source. The $ommand o!0ect ena!les access to data!ase commands to return data, modify data, run stored procedures, and so on. The .ata&eader provides a high"performance stream of data from the data source. Finally, the .ata-dapter provides the !ridge !etween the .ata,et o!0ect and the data source. The .ata-dapter uses $ommand o!0ects to e ecute ,U% commands at the data source to !oth load the .ata,et with data, and to update changes made to the data in the .ata,et !ack to the data source. 3. What is a data provider? E plain. Ans. - data provider is used for connecting to a data!ase, retrieving data, storing the data in a dataset, reading the retrieved data, and updating the data!ase. There are two types of data providers)

?< $oordinator 6uide 7 #asics of .NET

5NIIT

.LE <0 data provider) This type of data provider works with all the /%E .# providers, such as ,U% /%E .# provider, /racle /%E .# provider, and 4et /%E .# provider. The /%E .# .ata provider classes are present in the ,ystem..ata./le.! namespace. 2L erver data provider) This type of data provider is used to work specifically with 2icrosoft ,U% ,erver. - ,U% ,erver data provider is recommended for working with a 2icrosoft ,U% ,erver data source, !ecause a ,U% ,erver data provider allows fast access to a data source without going through an /%E .# or /.#$ layer. The ,U% ,erver data provider classes are present in the ,ystem..ata.,:l$lient namespace.

5NIIT

$oordinator 6uide 7 #asics of .NET ?8

4. What is a dataset? E plain. Ans. - dataset is a cached set of data!ase records. -./.NET is !ased on a disconnected data structure, therefore it is not possi!le for the application to interact with the data!ase for processing each record. Therefore, the data is retrieved and stored in datasets. - dataset is the most common method of accessing data as it implements a disconnected architecture. Cou can work with the records stored in a dataset as you work with real dataQ the only difference !eing that the dataset is independent of data source and you remain disconnected from the data source. -./.NET supports scala!ility !y working with datasets. .ata!ase operations are performed on the dataset instead of on the data!ase. -s a result, resources are saved, and the data!ase can meet the increasing demands of users more efficiently. The dataset acts like a virtual data!ase containing ta!les, rows, and columns. -n application works with the data!ase records stored in the dataset. 5. Write a program to show the demonstration of -./.NET. Ans. The following program demonstrates the use of -./.NET. Write the following code in the Clic? event of a !utton named .elete)
Private Sub 8eleteLClic? 4y3al sender 6s System.Ob@ect) 4y3al e 6s System.1vent6rgs! *andles 4utton%.Clic? 8im result 6s Integer 8im conn 6s 5e$ Ole8b.Ole8bConnection 'Provider&SX-O-184;7ser I8&sa;Pass$ord&;0rustedLConnection&yes;Initial Catalog&CallCenter%%;data source&local+ost'! conn.Open ! 8im delete1MP 6s Ole8b.Ole8bCommand & 5e$ Ole8b.Ole8bCommand 'delete /rom 1mployees $+ere 1mpI8&A1DDFA') conn! result & delete1MP.1(ecute5onXuery ! 1nd Sub

In the code given for the Clic? event of the .elete !utton, a connection o!0ect conn is created !y providing the information a!out the provider, the data source server, data!ase name that is to !e accessed, and the I. and password for connecting to the data source. Then, the connection with the data!ase is opened and a 8ataCommand o!0ect deleteE2* is created from the Ole8bCommand class. The 8ataCommand o!0ect deleteE2* is initiali>ed !y setting the ,U% statement to !e e ecuted using the Connection o!0ect conn. Then, the command is e ecuted and the num!er of rows affected !y the e ecution of the command is stored in an integer result.

Solutions to Chapter Eight Questions


1. What is a We! service? E plain its working. Ans. We! service refers to a platform on which you can !uild distri!uted applications. - We! service e poses a num!er of methods that provide functionality that can !e used !y one or more applications, regardless of the programming languages, operating systems, and hardware platforms used to develop them. In other words, a We! service ensures interopera!ility. $onsider the following figure.

?; $oordinator 6uide 7 #asics of .NET

5NIIT

Request

Client Application Response

Web Service

Communication 'et!een Client (pplication and )eb *er%ice

The functionality e posed !y a We! service can !e accessed !y applications !y using Internet standards, such as ,imple /!0ect -ccess *rotocol ',/-*(. ,/-* is a protocol that uses e tensi!le 2arkup %anguage '12%( to descri!e data and DyperTe t Transfer *rotocol 'DTT*( to transmit application data. -n application that uses a We! service is called a We! service client. The client sends a re:uest to the We! service. The cloud in the figure refers to the Internet. If the We! service calls some other service to get the answer or response, the We! service can take a while to respond. While it is waiting for the response, the client can perform other operations. 2. Dow is a We! service different from a We! page? Ans. The differences !etween a We! service and a We! page are listed in the following ta!le. Web Services +o ,ser -nterface -nteracts !ith application )or/s !ith any type of client Web Page .as a ,ser -nterface -nteracts !ith the user )or/s !ith !eb bro!ser client
)eb *er%ices #s. )eb "age

3. With a neat diagram, e plain the event handling process of We! forms. Ans. $onsider a We! form with a !utton. If a user clicks the !utton control, an event Clic? is raised for the !utton on the client computer. Dowever, the !rowser does not process the event. Instead, the !rowser raises a postbac? event so that the We! server is alerted a!out the Clic? event !eing raised. Ne t, the event handler written for the Clic? event is processed on the We! server and the output is sent to the client computer. 4. What is -,*.NET? Ans. -,*.NET is a framework for developing high performance We! applications. It is a compiled, .NET"!ased environment. Cou can write applications in any .NET compati!le language, including +#.NET, $H, and 4,cript .NET. -dditionally, the entire .NET Framework is availa!le to any -,*.NET application

5NIIT

$oordinator 6uide 7 #asics of .NET ??

5. What is the use of -,*.NET? Ans. -,*.NET provides a new programming model and infrastructure for more secure, scala!le, and sta!le applications. Cou can write applications in any .NET compati!le language, including +#.NET, $H, and 4,cript .NET. .evelopers can easily use the !enefits of these technologies, which include the managed $%& environment, type safety, inheritance, and so on. -,*.NET has !een designed to work seamlessly with What Cou ,ee Is What Cou 6et 'WC,IWC6( DT2% editors and other programming tools, including 2icrosoft +isual ,tudio .NET. Not only it makes We! development easier, !ut it also provides all the !enefits that tools offer, including a 63I that developers can use to drop server controls onto a We! page and fully integrated de!ugging support. %. Write a program to display JWelcome to -,*.NETK L times in increasing order of their font si>e !y using -,*.NET. Ans. The following program displays JWelcome to -,*.NETK eight times in increasing order of their font si>e. In the following code, the We! application name !ebApplication( is application specific)
<YZ Page language&'c#' Codebe+ind&'#ebCorm%.asp(.cs' 6uto1vent#ireup&'/alse' In+erits&'#eb6pplicationW.#ebCorm%' Y> <M8OC0=P1 *0M- P74-IC 'E//#FC//808 *0M- G.D 0ransitional//15' > <+tml> <+ead> <title>#ebCorm%</title> <meta name&',151.60O.' Content&'Microso/t 3isual Studio .510 V.%'> <meta name&'CO81L-65,76,1' Content&'C#'> <meta name&vsLde/aultClientScript content&'UavaScript'> <meta name&vsLtargetSc+ema content&'+ttpB//sc+emas.microso/t.com/intellisense/ieH'> </+ead> <body MSLPOSI0IO5I5,&',rid-ayout'> </orm id&'Corm9' met+od&'post' runat&'server'> <Y/or int i&D;i<T;iKK!"Y> </ont siNe&'<Y&iY>'>#elcome to 6SP.510 6S*IS*<//ont><br/><//ont> <Y2Y> <//orm> </body> </+tml>

&. What is the role of ,ystem.We!? Ans. The ,ystem.We! namespace supplies classes and interfaces that ena!le !rowser and server communication. This namespace includes the Dttp&e:uest class that provides e tensive information a!out the current DTT* re:uest, the Dttp&esponse class that manages DTT* output to the client, and the Dttp,erver3tility class that provides access to server"side utilities and processes. ,ystem.We! also includes classes for cookie manipulation, file transfer, e ception information, and output cache control. '. Write a program to demonstrate handling of server control events. Ans. 8. ;. ,elect tart Programs Microsoft Visual Studio .NET 2003 Microsoft Visual Studio .NET 2003 to open the Start Page of +isual ,tudio .NET I.E. ,elect 1ile#e63ro=ect to open the #e6 3ro=ect dialog !o .

?@ $oordinator 6uide 7 #asics of .NET

5NIIT

?. @. =.

,elect "isual C5 3ro=ects from the 3ro=ect $ypes pane and A 3.#E$ !eb Application from the $emplates pane. $lick the /V !utton. ,elect "ie6$oolbo, from the main menu. The $oolbo, window is displayed in the left pane. 3sing the !eb 1orms ta! of Tool!o , add the following controls to !eb1orm1.asp, and change the properties of the controls, as shown in the following ta!le. Control Type Text 1irst +ame lblfname t2tfname 0ast +ame lbllname t2tlname ,ser +ame lbluname t2tuname "ass!ord lblpass!ord t2tpass!ord Confirm "ass!ord lblcpass!ord t2tcpass!ord (ddress lbladdress t2taddress City lblcity t2tcity *tate lblstate t2tstate "ostal Code lblpcode t2tpcode Country lblcountry ddlcountry Telephone no. lbltelno t2ttelno 4-mail -d lblemail t2temail lblmessage *ubmit btnsubmit ID

0abel Te2t'o2 0abel Te2t'o2 0abel Te2t'o2 0abel Te2t'o2 0abel Te2t'o2 0abel Te2t'o2 0abel Te2t'o2 0abel Te2t'o2 0abel Te2t'o2 0abel 3rop3o!n0ist 0abel Te2t'o2 0abel Te2t'o2 0abel 'utton

3escription of the Controls to be (dded in the )eb 1orm

5NIIT

$oordinator 6uide 7 #asics of .NET ?=

A. I. L. N.

The te t !o es for 3ass6ord and Confirm 3ass6ord fields need to display asterisks 'O( when a user enters a value. To ena!le this, set the $e,t*ode property of these two te t !o es to 3ass6ord in the 3roperties window. -dd three -e8uired1ield"alidator controls to the !eb1orm1.asp, form !y using the !eb 1orms ta! of the Tool!o . -dd one Compare"alidator control to the !eb1orm1.asp, form !y using the !eb 1orms ta! of the Tool!o . .ou!le"click the !eb1orm1.asp, form to open the code"!ehind file with a .cs e tension. In the -oad event of the page, enter the following lines of code)
ddlcountry.Items.6dd '4anglades+'!; ddlcountry.Items.6dd '4+utan'!; ddlcountry.Items.6dd 'India'!; ddlcountry.Items.6dd '5epal'!; ddlcountry.Items.6dd 'Pa?istan'!; ddlcountry.Items.6dd 'Sri -an?a'!; Compare3alidator%.Control0o3alidate&'t(tcpass$ord'; Compare3alidator%.Control0oCompare&'t(tpass$ord'; Compare3alidator%.0e(t&'0+e values o/ Pass$ord and Con/irm Pass$ord /ields does not matc+'; .eOuiredCield3alidator%.Control0o3alidate&'t(tuname'; .eOuiredCield3alidator%.0e(t&'Please enter a user name'; .eOuiredCield3alidator9.Control0o3alidate&'t(tpass$ord'; .eOuiredCield3alidator9.0e(t&'Please enter a pass$ord'; .eOuiredCield3alidatorF.Control0o3alidate&'t(tcpass$ord'; .eOuiredCield3alidatorF.0e(t&'Please reEenter t+e pass$ord';

8<. In the $lick event of btnsubmit, enter the following code)


i/ Is3alid! " lblmessage.0e(t&'#elcome 'K t(t/name.0e(t K' 'Kt(tlname.0e(t K '.=ou +ave success/ully registered.'; 2

88. E ecute the application.

Solutions to Chapter Nine Questions


1. What is .NET &emoting? Ans. &emoting is the process of communication !etween different processes, regardless of whether they are on the same or different computers. The .NET remoting system is an architecture designed to simplify communication !etween o!0ects e isting in different application domains whether or not on the same computer. It also simplifies communication !etween different conte ts whether or not in the same application domain. 2. Dow is .NET &emoting different from We! services and .$/2? Ans. The differences !etween .NET &emoting and We! services are listed as follows) -,*.NET !ased We! services can only !e accessed over DTT*, whereas the .NET &emoting can !e used across any protocol. We! services work in a stateless environment where each re:uest results in a new o!0ect created to service the re:uest. .NET &emoting supports state management options and can identify multiple calls from the same client. We! services seriali>e o!0ects through 12% contained in the ,/-* messages and can thus only handle items that can !e fully e pressed in 12%. .NET &emoting relies on the e istence of the metadata within assem!lies that contain information a!out data types. This limited metadata information is passed a!out an o!0ect, when it is passed !y reference.

?A $oordinator 6uide 7 #asics of .NET

5NIIT

We! services support interopera!ility across platforms and are good for heterogeneous environments. .NET &emoting re:uires the clients to !e !y !uilt using .NET, which means a homogeneous environment.

The difference !etween .NET &emoting and .$/2 is listed as follows) .$/2 relies on a proprietary !inary protocol that not all o!0ect models support. It also wants to communicate over a range of ports that are typically !locked !y firewalls. Dowever, .NET &emoting supports different transport protocol formats and communication protocols. This allows .NET &emoting to !e adapta!le to the network environment in which it is !eing used.

3. E plain remoting architecture. Ans. The remoting architecture consists of the remote component, server, client, and a transportation medium that ena!les communication !etween the client and the server. These components are e plained !elow. The remote component is the o!0ect that provides services to the client. The server creates and register a channel, which is a transportation medium, to listen at a specified port. The server also registers the remote o!0ect. - channel is a transportation medium through which communication !etween a server and a client takes place. The client re:uests for the services of a remote o!0ect. - client can choose the registered channels on the server to communicate with the remote o!0ect. Note) The process !y which the interaction takes place !etween these components is e plained in the following answer. 4. With a neat diagram e plain the remoting process. Ans. The primary function of remoting is to communicate !etween server and client !y using o!0ects. -fter the client is configured properly, a new instance of the remote o!0ect is created. *ro y o!0ects are used !y the remoting system. *ro ies are those o!0ects that present themselves as some other o!0ects. The infrastructure of remoting creates pro y o!0ects when a user generates an instance of remote types. To the user, this pro y o!0ect will look e actly similar to the remote o!0ects. In this pro y o!0ect, the user calls a method and the call is received !y the remoting system. The method is then routed to the server and it invokes the server o!0ect. -fter invoking the server o!0ect, a value is returned that is sent !ack to the client pro y. This will provide the results to the user. The communication !etween server and client is done !y using a channel. - channel carries the data stream, makes a package related to a particular protocol, and sends the package to a different computer. In remoting architecture, the process of remoting is designed considering the security factor. The remoting process is illustrated in the following figure.

-emoting ystem

-emoting ystem
3ro,y

erver .b=ect

Client .b=ect

5NIIT

C+annel $oordinator 6uide 7 #asics of .NET ?I $arries a stream of data, makes a package related to a particular protocol, and sends the package to a different computer.

$emoting "rocess 5. E plain the steps or phases involved in implementing .NET remoting applications. Ans. The phases involved in implementing .NET remoting applications are) 8. ;. ?. $reate a remota!le o!0ect) - remota!le o!0ect is an o!0ect that inherits from 2arshal#y&ef/!0ect. $reate a server to e pose the remote o!0ect) - server o!0ect acts as a listener to accept remote o!0ect re:uests. $reate a client to use the remote o!0ect) - client o!0ect will connect to the server, create an instance of the o!0ect using the server, and then e ecute the remote methods.

%. Write a program to demonstrate .NET remoting. Ans. The steps involved in implementing .NET remoting applications are) 8. $reate a remota!le o!0ect. -dd the following code in the code window of a $lass %i!rary)
using System; namespace .emote0est " public class 0est-oader B System.Mars+al4y.e/Ob@ect " public 0est-oader ! " System.Console.#rite-ine '*ello #orld'!; 2 public string 0est ! " string stc&'Client'; return stc; 2 2 2

#uild the code. ;. $reate a server to e pose the remote o!0ect. -dd the following code in the code window of a $onsole -pplication)
using using using using using using using System; System..untime; System..untime..emoting; System..untime..emoting.C+annels; System..untime..emoting.C+annels.0cp; System.IO; .emote0est;

namespace Server " class ClassServer " static void Main String:; args! "

?L $oordinator 6uide 7 #asics of .NET

5NIIT

0cpServerC+annel c+annel & ne$ 0cpServerC+annel WWF9!; C+annelServices..egisterC+annel c+annel!; .emotingCon/iguration..egister#ell[no$nService0ype typeo/ 0est-oader!) '0est-oader') #ell[no$nOb@ectMode.SingleCall!; System.Console.#rite-ine '*ello Crom Server'!; System.Console..ead-ine !; 2 2 2

,et a reference to &emoteTest.dll file and ,ystem.&untime.&emoting. The &emoteTest.dll file will !e located in &emoteTest 9!in9.e!ug. #uild the server code. ?. $reate a client to use the remote o!0ect. -dd the following code in the code window of a $onsole -pplication)
using using using using using System; System..untime..emoting; System..untime..emoting.C+annels; System..untime..emoting.C+annels.0cp; .emote0est;

namespace Client " class ClassClient " static void Main string:; args! " try " C+annelServices..egisterC+annel ne$ 0cpClientC+annel !!; 0est-oader loader & 0est-oader!6ctivator.,etOb@ect typeo/ .emote0est.0est-oader!) 'tcpB//local+ostBWWF9/0est-oader'!; string res & loader.0est !; Console.#rite-ine '*ello Crom 'K res!; 2 catc+ 1(ception e! " Console.#rite-ine '7nable to get remote re/erence' K e!; 2 System.Console..ead-ine !; 2 2 2

,et a reference to &emoteTest.dll file and ,ystem.&untime.&emoting. The &emoteTest.dll file will !e located in &emoteTest 9!in9.e!ug. #uild the client program. E ecute the server program followed !y the client program.

5NIIT

$oordinator 6uide 7 #asics of .NET ?N

Você também pode gostar