53
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 exists as a layer between the .NET applications and the underlying operating system. The .NET Framework encapsulates much of the basic functionality, such as debugging and security services, which was earlier built into various programming languages. 2. What does .NET Framework consists of? Ans. The .NET Framework consists of Web forms, Windows forms, and console applications that pertain to the presentation layer of an application. Web forms are used in Web-based applications, whereas Windows Forms are used in Windows-based applications for providing an interactive user interface. In addition, you can create character-based console applications that can be executed from the command line. Besides these three components, the .NET Framework consists of two other components, the .NET Framework Base Classes and the Common Language Runtime (CLR). 3. Write a note on: a. Programming methodologies Ans. The Visual Studio .NET programming methodology allows for mixed-language programming. This is established through a Common Type System (CTS) that is defined for all the languages that .NET Framework supports. All these languages compile into an intermediate language before 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. Platform technologies Ans. The .NET Framework includes platform technologies like ADO.NET, ASP.NET, and VB.NET. ADO.NET allows .NET applications to communicate with a database for retrieving, accessing, and updating data. ASP.NET is a framework for building enterprise-class Web applications. VB.NET is an object-oriented language that provides features such as abstraction, encapsulation, and polymorphism. By using these technologies, you can easily develop robust Web applications, Windows applications, and XML Web services. c. Code execution Ans. The code execution process involves the conversion of Intermediate Language into native or CPU-specific code. The CLR is completely architecture-neutral. All the .NET languages get compiled into the IL. This intermediate language gets compiled by Just-in-Time (JIT) compiler into the native machine code. After translating the IL into native code, the converted

Solutions to Chapter One Questions 61

Embed Size (px)

DESCRIPTION

Solutions to Chapter One Questions 61 Bsc it

Citation preview

  • 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 exists as a layer between the .NET applications and the underlying operating system. The .NET Framework encapsulates much of the basic functionality, such as debugging and security services, which was earlier built into various programming languages. 2. What does .NET Framework consists of? Ans. The .NET Framework consists of Web forms, Windows forms, and console applications that pertain to the presentation layer of an application. Web forms are used in Web-based applications, whereas Windows Forms are used in Windows-based applications for providing an interactive user interface. In addition, you can create character-based console applications that can be executed from the command line. Besides these three components, the .NET Framework consists of two other components, the .NET Framework Base Classes and the Common Language Runtime (CLR). 3. Write a note on: a. Programming methodologies Ans. The Visual Studio .NET programming methodology allows for mixed-language programming. This is established through a Common Type System (CTS) that is defined for all the languages that .NET Framework supports. All these languages compile into an intermediate language before 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. Platform technologies Ans. The .NET Framework includes platform technologies like ADO.NET, ASP.NET, and VB.NET. ADO.NET allows .NET applications to communicate with a database for retrieving, accessing, and updating data. ASP.NET is a framework for building enterprise-class Web applications. VB.NET is an object-oriented language that provides features such as abstraction, encapsulation, and polymorphism. By using these technologies, you can easily develop robust Web applications, Windows applications, and XML Web services.

    c. Code execution Ans. The code execution process involves the conversion of Intermediate Language into native or CPU-specific code. The CLR is completely architecture-neutral. All the .NET languages get compiled into the IL. This intermediate language gets compiled by Just-in-Time (JIT) compiler into the native machine code. After translating the IL into native code, the converted

  • code is sent to the .NET runtime manager. The .NET runtime manager executes the code. While executing the code, a security check is performed to ensure that the code has the appropriate permissions for accessing the available resources. 4. Which are the platform technologies supported by .NET Framework? Ans. Some of the platform technologies supported by .NET Framework are: ADO.NET ASP.NET VB.NET 5. List the advantages of .NET Framework. Ans. The .NET Framework offers the following advantages: Consistent programming model: The base classes of the .NET class library provide

    standard functionality such as, input/output, remoting, thread management, string manipulation, user interface design, and security management. The ADO.NET classes allow developers to access data in the form of XML. XML classes enable developers to read, write, manipulate, and transform XML files. The ASP.NET classes support the development of Web-based applications and Web services. The Windows forms classes support the development of desktop-based applications. Together, the .NET class library provides a common functionality to all .NET languages resulting in a consistent object model regardless of the programming language used by 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 interoperability 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 required by an application, even if several versions of the same application exist on the computer. The .NET Framework ensures that all the components on which the application depends are available on the computer before the application begins to run. Visual Studio 2005 includes a new application deployment technology known as ClickOnce, which allows you to easily deploy a Windows forms application. ClickOnce enables 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 unauthorized users: Code Access Security (CAS) uses permissions to control the code accessing

    protected resources and operations. Role-based security provides information needed to make decisions about user

    permissions. Support for Web services: With the advent of .NET technology, Web services provide

    many built-in BCL facilities that allow different applications from different sources to communicate with each other. Web services do not provide the user with a GUI. Web services instead share business logic, data and processes through a programmatic interface across a network.

  • Ease of creating dynamic Web content: Dynamic Web content is easier to create with .NET. ASP. NET 2.0 includes various features that enable you to easily develop Web applications having a consistent layout and appearance.

    Visual Studio .NET: Visual Studio .NET is the Microsoft application and interface for programming in .NET. Visual Studio .NET provides all the programming advantages mentioned so far. This development environment has an extensive set of ready-to use-controls, good debugging facilities, easy and simple programming features, and a vast set of .NET base classes. All these features enable you to develop high performance applications in a short period of time.

    6. What is backward compatibility? Ans. Backward compatibility refers to the ability of a technology to work with its previous versions or with other earlier technologies. For example, the Active Directory structure of Windows 2000 is backward compatible with Windows NT 3.51 and 4.0. Similarly, the .NET Framework supports backward compatibility. For example, you can compile and run applications created in Visual Basic 6.0 in Visual Studio 2005. 7. Does .NET platform support backward compatibility? Explain. Ans. The .NET platform supports backward compatibility. It is possible for an application compiled in one version of the .NET Framework to run on a different version of the .NET Framework. For example, you can run applications developed in Visual Studio 2002/2003 on Visual Studio 2005. In addition to the above example, the .NET platform supports backward compatibility in the following ways: The .NET Framework 2.0 BCL supports backward compatibility with the earlier

    versions. .NET supports C++ because of backward compatibility. To run a C++ code on .Net

    Framework, you need to include the following line at the beginning of the code: #using

    VB applications can work on VB.NET and ASP applications can run on ASP.NET because of backward compatibility.

    You can easily reference COM components in.NET applications. FAQs 1. What are the different types of application architectures? Ans: The different types of application architectures are: Single-tier: A single application handles all functions related to the user, business, and

    data service layers. Such an application is also called a monolithic application. Two-tier: The two-tier architecture divides an application into the following two

    components: Client: Implements the user interface Server: Stores data

  • The business logic can either be integrated with the client (fat client) or with the server (fat server).

    Three-tier: In the case of three-tier architecture, all the three service layers reside separately, either on the same machine or on different machines. The user interface interacts with the business logic. The business logic validates the data sent by the interfaces and forwards it to the database if it conforms to the requirements. The front-end only interacts with business logic, which, in turn, interacts with the database.

    n-tier: An n-tier application uses business objects for handling business rules and data access. It has multiple servers handling business services. This application architecture provides various advantages over other types of application architectures. Some of the advantages include extensibility, resilience to change, maintainability, and scalability of the application.

    2. What is the difference between a project and a solution? Ans: In Visual Studio .NET, an application can be made up of one or more items, such as files and folders. To organize these items efficiently, Visual Studio .NET has provided two types of containers, projects and solutions. A project typically contains items that are interrelated. Items can be forms, references, and data connections. For example, you may create a project that contains a form for accepting user details and database connection for transferring these details to a database. A project allows you to manage, build, and debug the items that make up an application. When you build a project, it usually results in the creation of an executable file (.exe) or a dynamic link library (.dll). These files that are created as a result of building the project are called the project output. A solution usually acts as a container for one or more projects. For example, you may create a solution containing two projects, one for manipulation of data and the other for generation of reports for the sales division of an organization. Thus, a solution allows you to work on multiple projects within the same instance of the Visual Studio .NET IDE. A solution also allows you to specify settings and options that apply to multiple projects. 3. What does the Visual Studio .NET IDE provide? Ans: The Visual Studio .NET IDE provides you with a common interface for developing various kinds of projects for the .NET Framework. The IDE provides you with a centralized location for designing the user interface for the application, writing code, and compiling and debugging the application. The Visual Studio .NET IDE is available to all the programmers who use the languages in the Visual Studio .NET suite. 4. Why is XML used as a common data format to transfer data among applications? Ans: XML is a cross-platform, hardware and software independent markup language. XML allows computers to store data in a format that can be interpreted by any other computer systems. Therefore, XML can be used to transfer structured data between heterogeneous systems. XML is used as a common data interchange format in a number of applications. 5. What is Whidbey? Ans:

    Whidbey is the code name of Visual Studio 2005, which was released in November 200

  • Solutions to Chapter Two Questions 1. With a neat diagram, explain the .NET Framework architecture. Ans. The .NET Framework is the foundation on which you design, develop, and deploy applications. The .NET Framework consists of ASP.NET Web Forms, Windows Forms, and Console applications that pertain to the presentation layer of an application. Web Forms are used in Web-based applications, whereas Windows Forms are used in Windows-based applications for providing an interactive user interface. In addition, you can create character-based console applications that can be executed from the command line. Besides these three components, the .NET Framework consists of two other components, the .NET Framework Base Classes and the CLR. 2. List out the objectives of the .NET Framework. Ans. The objectives of .NET Framework are: To provide an object-oriented programming environment and to determine whether

    object code is stored and executed locally, or executed remotely. To provide a code-execution environment that minimizes software deployment and

    versioning conflicts. To provide a code-execution environment that guarantees safe execution of code,

    including code created by an unknown or semi-trusted third party. To provide a code-execution environment that eliminates the performance problems of

    scripted or interpreted environments. To ensure consistency across varying types of applications, such as Windows-based

    applications and Web-based applications. To build all communication on industry standards to ensure that code based on the .NET

    Framework can integrate with any other code. 3. How is Windows Programming different from .NET Programming. Ans. In Windows Programming, the application programs call Windows API 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 Programming, the application calls the .NET BCL functions which communicate with the operating system. The applications run in .NET Runtime environment. These types of applications are called managed or safe applications. The .NET Runtime starts code execution, manages threads, provides services, and manages memory. 4. Define the following: CLR Ans. The CLR loads and executes the code. Code management is a fundamental principle of the runtime. It also provides services such as memory management, thread management, remoting, type safety, code security, and robustness. Managed code Ans. The code that is developed with a language compiler that targets the CLR is called managed code. Managed code is designed to run on .Net environment. Intermediate language Ans. In the .NET framework, all the .NET languages get compiled into the MSIL or simply the Intermediate Language (IL). The intermediate language is analogous to the byte code of Java. The significant difference is that the byte code is interpreted while the IL is compiled by JIT compilation to native machine code. CTS

  • Ans. The CTS is a standardized set of basic data types. This system provides a way to language interoperability. An object implemented in one .NET supported language can call an object implemented in another .NET supported language. .NET Base Classes Ans. NET Base Classes is a library consisting of an extensive set of functions for all services supported by the Framework. This class library provides classes that can be used in the code to accomplish a range of common programming tasks such as string management, data collection, database connectivity, and file access. Assemblies Ans. Assembly is the unit in which compiled managed code is stored. An assembly contains IL and metadata. Metadata gives details of the assembly, properties and methods stored in it, and security information. CLS Ans. Common Language Specification (CLS) is a set of rules for basic language features that have been defined to enhance and ensure language interoperability. Reflection Ans. Reflection is the process of obtaining information about assemblies and the types defined within them as metadata at runtime. JIT compilation Ans. JIT compilation converts IL into its native machine code. The name JIT is because it compiles portion of code as and when required at runtime.

    Manifest Ans. Manifest is the area of the assembly where metadata is stored. Application domain Ans. Application domain is the boundary that the CLR establishes around objects created within the same application. Application domain allows different code to run in the same process space. Garbage collection Ans. The garbage collection feature relieves the programmer from the responsibility of freeing memory when no longer required. The CLR calls the garbage collector to handle memory efficiently. 5. What are the functionalities of CLR? Give the steps involved in the managed execution process. Ans. The CLR has the following functionalities: The CLR uses metadata to locate and load classes, lay out instances in memory, resolve

    method invocations, generate native code, enforce security, and set runtime context boundaries.

  • The CLR automatically handles object layout and manages references to objects, releasing them when they are no longer being used. Automatic memory management eliminates memory leaks as well as some other common programming errors.

    The CLR makes it easy to design components and applications whose objects interact across languages. Objects written in different languages can communicate with each other, and their behaviors can be tightly integrated.

    The managed execution process includes the following steps: 1. Choosing an appropriate language compiler. 2. Compiling your code to MSIL or simply IL: Compiling translates your source code into

    IL and generates the required metadata. 3. Compiling IL to native code: At execution time, a JIT compiler translates the IL into the

    native machine code. During this compilation, the code must pass a verification process that examines the IL and metadata to find out whether the code can be determined to be type safe.

    4. Executing code: The CLR provides the environment that enables execution as well as a variety of services that can be used during execution.

    6. What are assemblies? What are static and dynamic assemblies? Ans. Assembly is a basic element of packaging in .NET. An assembly consists of IL code, metadata that describes what is in the assembly, and any other files or information that the application needs to run, such as graphics and sound files. Assemblies can be static or dynamic. Static assemblies can include .NET types (interfaces and classes), as well as required resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in Portable Executable (PE) files. Dynamic assemblies are the ones that run directly from the memory, and are not saved on disk before execution. They can be saved on the disk after they have been executed.

    7. How does the .NET execution environment with application domain differ from the traditional way of execution?

    Ans. In the case of .NET Framework, application domains provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications. Several application domains can be run in a single process with the same level of isolation that would exist as separate processes, but without incurring the additional overhead of making IPC calls or switching between processes. Traditionally, the process boundaries have been 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. As a result, the process cannot make direct calls to another process. Instead, IPC techniques have to be used to have communication between the processes. Each application is a separate process. 8. What is the function of CTS? Explain the classification of types in CTS with the help of a diagram. Ans. The CTS defines how types are declared, used, and managed in the runtime. It is important for language interoperability. The CTS performs the following functions: Establishes a common framework that enables cross-language integration, type safety,

    and high performance code execution. Provides an object-oriented model.

  • Defines rules that languages must follow, so that different languages can interact with each other.

    CTS can be classified into: Value types Reference types The following diagram illustrates type classification.

    Type Classification

    Value types directly store data in the variable. Value types can be built-in type, user-defined types, or enumerations. Reference types store a reference to the data's memory address. Reference types can be self-describing types, pointer types, or interface types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates. All types derive from the System.Object base type. 9. Write a note on metadata. Ans. An assembly stores all the information about itself. This information is called metadata and includes the name and version number of the assembly, security information, information about the dependencies, and a list of the files that constitute an assembly. Metadata is the binary information describing the program. When we compile our code into a PE file, the metadata is inserted into one portion of the PE file, while the code is converted to IL and inserted into another portion of the PE file. Every type member that are defined or referenced in a module is described within metadata. When code is executed, the runtime loads metadata into memory and refers it to get information about the code's classes, members, inheritance, and so on. Metadata allows .NET languages to describe themselves in a language-neutral manner. It gives required information to the CLR to perform much of its functionalities. The presence of metadata makes the assembly self-describing file. The CLR modules or components or other assemblies which want to communicate with each other use this information stored in metadata to perform their tasks.

    Type

    Value Types Reference Types

    Built-In-Value Types

    User-Defined Value Types

    Enumerations

    Self Describing Types

    Pointer Types

    Interface Types

    Class Types Arrays

    User-Defined Classes

    Boxed Value Types

    Delegates

  • 10. It is told that if we learn any one .NET language, then working with other .NET languages will be easy. How? Explain with an appropriate example. Ans. It can be told that if you have learned any one .NET language, then working with other .NET languages will be easy. This is because all the .NET languages rely on the same managed classes of BCL for the same services. The same classes, methods, parameters, and types are used for all the system services regardless of any .NET language. Let 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() { StreamWriter sw1=new StreamWriter("temp.txt", true); string tempstring="Hi, this is Gopal"; sw1.WriteLine(tempstring); sw1.Close(); StreamReader sr1=new StreamReader("temp.txt"); string filestring=sr1.ReadToEnd(); sr1.Close(); Console.WriteLine(filestring); }

    // Program in VB.NET shared public sub Main() dim sw1 as StreamWriter=new StreamWriter("temp.txt", true) dim tempstring as string= "Hi, this is Gopal" sw1.WriteLine(tempstring) sw.Close() dim sr1 as StreamReader=new StreamReader("temp.txt") dim filestring as string=sr1.ReadToEnd() sr1.Close() Console.WriteLine(filestring) end sub

    If we see, both versions of the above program are nearly identical. The syntax and use of StreamReader, StreamWriter, and the Console class are identical, same methods, and identical parameters.

    FAQs 1. What is BCL? Ans: The BCL is an object-oriented library of pre-packaged functionality. 2. What is the difference between managed code and managed data? Ans: The code that targets the functionalities of the CLR is known as the managed code. C#, VB.NET, and Jscript.NET code is managed by default. However, C++ code is not managed by default. Managed data refers to the data that is allocated and deallocated by the garbage collection feature of the CLR.

  • 3. What is the difference between an assembly and a namespace? Ans: An assembly is a single deployable unit that contains all the information about the implementation of classes, structures, and interfaces. Namespaces help you create logical groups of related classes and interfaces that can be used by any language targeting the .NET Framework. 4. What is GAC? Ans: When you create an assembly, it can be accessed by only the local application that created it. However, multiple applications might require accessing the same assembly. In such situations, you need to store the assembly at a central location. This is done by adding the assembly to the Global Assembly Cache (GAC). GAC is a machine-wide code cache that is used to store assemblies that are created to be shared by multiple applications. You need to assign a strong name to the assemblies before adding it to the GAC. An assembly can be added to the GAC by using the following methods: Using the Windows installer. (The installer used must be compatible with the GAC.) Using the Gacutil.exe that is the GAC tool. Using the Windows drag and drop feature. 5. Differentiate between a .dll and a .exe. Ans: A .dll runs in the same memory process as the container. This means that if the .dll is corrupted, it will cause the parent application to crash. An .exe on the other hand runs in a different memory process. This means that even if the .exe gets corrupted, the parent application will not be harmed. However, execution of an .exe is slower as compared to .dll. 6. In which file are the assembly details like assembly name and version number stored? Ans: AssemblyInfo.cs

  • Solutions to Chapter Three Questions 1. List out the important features of C#. Ans. The features of C# are as follows: C# is an elegant, simple, type-safe, object-oriented language. C# has the capability to build durable system-level components due to the following

    features: Full COM/platform support for existing code integration Robustness through garbage collection and type safety Security provided through good design Full support of extensible metadata concepts

    C# supports language interoperability and platform independence. 2. Write a program in C# to display Welcome to the world of C Sharp. Explain the program. Ans. The C# program is as follows:

    using System; namespace ConsoleApplication1 { class Welcome { static void Main() { System.Console.WriteLine("Welcome to the world of C Sharp"); Console.Read(); } } }

    The important points to be noted in this program are: Main method: Program execution begins with the Main method. Input and output: The WriteLine function displays the string on the standard output

    device. Compilation and execution: To compile the program, enter the following command:

    csc Welcome.cs To execute the program, enter the following command: Welcome

    3. Explain the general structure of a C# program. Ans. C# program can consist of one or more files. Each file can contain one or more namespaces. A namespace contains group of related types such as classes, structs, interfaces, enumerations, and delegates. Namespaces may be nested. The following is the structure of a C# program that contains all of these elements:

    using System; //Using the System Namespace

  • namespace Namespace1 //Defining a namespace { class Class1 //Defining a class { } struct Struct1 // Defining a structure { } interface Interface1 //Defining an interface { } delegate int Delegate1(); enum Enum1 //Defining an enumeration { } namespace Namespace2 //Defining a namespace { } class Class2 //Defining a class { public static void Main(string[] args) //Program execution begins //from here { } } }

    4. How do namespaces and types in C# have unique names? Give an example. Ans. Namespaces and types always have unique names. If there are two classes with the same name but present in different namespaces, then both the objects will have unique fully qualified names. Consider the following code snippet:

    namespace ABC // ABC { class Class1 // ABC.Class1 { } } namespace XYZ // XYZ { class Class1 // XYZ.Class1 { } }

    Here the ABC.Class1 and XYZ.Class1 are two different types, even if the class name is same. 5. List out the difference between C# and C++. Ans. The differences between C# and C++ are as follows.

    C# C++

    C# is a purely object-oriented language. C++ supports object-oriented programming.

  • C# C++

    The long data type is of 64 bits. The long data type is of 32 bits.

    C# supports ref and out parameters, which are used instead of pointers in passing parameters by reference. Pointers are allowed in C# but only in the unsafe mode.

    C++ supports pointers in passing parameters by reference.

    C# Vs. C++ FAQs

    1. Can you use the using statement with multiple objects? Ans: You can use the using statement with multiple objects by nesting using statements, as shown in the following code snippet:

    using (object1); using (object2);

    Consider the following code snippet: using (StreamWriter w1 = File.CreateText("SW1")) { using (StreamWriter w2 = File.CreateText("SW2")) { // code here } }

    You can simplify the above code by writing: using (StreamWriter w1 = File.CreateText("SW1")) using (StreamWriter w2 = File.CreateText("SW2")) { // code here }

    The above code snippet illustrates the use of nested using statements. 2. Has C# got its own class library? Ans: C# has not got its own class library. It uses the class library of the .NET Framework.

    3. How will you compile Test1.cs to produce NewFile.exe? Ans: You need to type the following command to implement this task:

    csc /out:NewFile.exe Test1.cs 4. How will you compile Test1.cs to produce a dll file? Ans: You need to type the following command to implement this task:

    csc /target:library Test1.cs

  • Solutions to Chapter Four Questions 1. Which are the two different categories of types in C#? Ans. In C# language, the types are divided into two categories: Value types: Variables of the value types directly contain their data. With value types,

    the variables have their own copy of the data. Reference types: Variables of the reference types store address of their data. With

    reference types, it is possible for two variables to reference the same object.

    2. What are variables? How many categories of variables are there in C#? Define each. Ans. Variables represent storage locations. Every variable has a type that determines what kind of data can be stored in the variable. There are seven categories of variables: Static variables: A variable declared with the static modifier is called a static variable.

    There will be only one copy of the variable, regardless of how many instances of class (in which static variable exists) are created.

    Instance variables: A variable declared without the static modifier is an instance variable.

    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 existence when an array instance is created and exists until there are no references to that array instance.

    Value parameters: Parameters are arguments passed to the function. A parameter declared without a ref or out modifier is a value parameter. A value parameter comes into existence when the function is invoked and is initialized with the value of the argument passed. A value parameter exists until the function returns.

    Reference parameters: A parameter declared with a ref modifier is a reference parameter. A reference parameter does not create a new instance, it points to the same storage location of the parameter passed as an argument.

    Output parameters: A 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: A local variable is declared within a block, like a for-statement, a switch-statement, or a using-statement. A local variable is not automatically initialized and thus has no default value.

    3. What is the importance of automatic memory management? Explain with example. Ans. Manual memory management requires developers to manage the allocation and de-allocation of blocks of memory. Manual memory management can be both time consuming and difficult. In C#, automatic memory management is provided so that developers are freed from this manual task. Automatic memory management increases code quality and enhances developer productivity without negative impact on either expressiveness or performance. Consider the following example:

    using System; public class Stack {

  • private Node first = null; public bool Empty { get { return (first == null); } } public object Pop() { if (first == null) Console.Write("Can't Pop from an empty Stack."); else { object temp = first.Value; first = first.Next; return temp; } } public void Push(object o) { first = new Node(o, first); } class Node { public Node Next; public object Value; public Node(object value): this(value, null) {} public Node(object value, Node next) { Next = next; Value = value; } } }

    In the above example, a Stack class is implemented as a linked list of Node instances. These node instances are created in the Push method and are deallocated when no longer in use. 4. Write a note on expressions and operators in C#. Ans. An expression is a sequence of operators and operands that specifies computation and assigns the result to a variable. Expressions are constructed from operands and operators. The operators of an expression indicate which operations to perform. Examples for operators are +, -, *, /, etc. Examples for operands are literals, variables, and expressions. There are three kinds of operators: Unary operators: The unary operators operate on only one operand. For example, --x,

    x++. Binary operators: The binary operators operate on two operands. For example, x + y. Ternary operator: The ternary operator operates on three operands. For example,

    condition? true_exp: false_exp. There is only one ternary operator, ?:. The order of evaluation of operators in an expression is determined by the precedence and associability of the operators. When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has a higher precedence than the + operator.

  • 5. What are empty statement and labeled statements? Why are they used? Ans. An empty statement (;) is used when there are no operations to perform. Execution of an empty statement simply transfers control to the end point of the statement. For example, an empty statement can be used when writing a while statement with a null body:

    while (WaitForAnEvent()) ;

    An empty statement can also be used to declare a label just before the closing } of a block: void Func() { ... if (true) goto exit; ... exit: ; }

    A labeled statement is prefixed by a label of a character string. Labeled statements are permitted in blocks. A label is a name given by the identifier. The scope of a label is the block in which the label is declared. If two labels have the same name, you get a compile time error. A label can be referenced from goto statements within the scope of the label. Labels and other identifiers can have the same name. Consider the following example:

    int Func(int abc) { if (abc >= 0) goto abc; abc = -abc; abc: return abc; }

    The above example uses the name abc as both a parameter and a label. 6. What is an iterative statement? Explain foreach statement with example. Ans. Iteration statements repeatedly execute a block of statements. The number of iterations depends on the condition represented by the boolean expression. The block of code will be iterated until the condition is true. Consider the following code:

    using System; class TestForeach { static void Main() { int[] array1 = new int[] {1,2,3,4,5}; foreach (int i in array1) Console.WriteLine(Value is {0}, i); } }

    In the above example, the foreach statement iterates through the elements of array1.

  • 7. List the different jump statements supported by C#. Ans. The different jump statements supported by C# are: break statement continue statement goto statement return statement throw statement 8. What are checked and unchecked statements? Give an example. 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 expressions in the checked block to be evaluated in a checked context, and the unchecked statement causes all expressions in the unchecked block to be evaluated in an unchecked context. Checked allows you to raise an exception whenever stack overflow (or underflow) occurs due to type conversion issues. Unchecked will allow you to ignore these exceptions when the C# project is set to raise these types of exceptions. Consider the following example:

    static void Main() { int x = Int32.MaxValue; Console.WriteLine(x + 1); // Overflow checked { Console.WriteLine(x + 1); // Exception } unchecked { Console.WriteLine(x + 1); // Overflow } }

    In the above example, the checked keyword allows you to report the overflow at runtime. 9. Give an example of lock and using statements. Ans. Example of lock statement:

    static void Main() { A a = ...; lock(a) { a.P = a.P + 1; } }

    In the above code snippet, a block of code obtains a mutual-exclusion lock. Example of using statement:

    static void Main() { using (Resource r = new Resource()) {

  • r.Func(); } }

    In the above code snippet, resources are obtained with the using statement. 10. How are structures different from classes in C#? Ans. Structures are value types and classes are reference type. A variable of a structure type directly contains the data of the structure, whereas a variable of a class type contains a reference to the object. You can inherit classes but you cannot inherit structures. 11. What are interfaces? Give an example. Ans. Interfaces are used to define a contract; a class or struct that implements the interface must obey to this contract. Interfaces can contain methods, properties, indexers, and events as members. They cannot contain constants, fields (private data members), constructors, and destructors, or any type of static member. All the members of an interface are public by definition. Consider the following example:

    interface IExample { string this[int index] { get; set; } event EventHandler E; void Func(int value); string P { get; set; } } public delegate void EventHandler(object sender, EventArgs e);

    The above example shows an interface that contains an indexer, an event E, a method Func, and a property P.

    12. What is a delegate? What is the use of it? Give an example. Delegates are objects that you use to call the methods of other objects. Delegates are said to be object-oriented function pointers since they allow a function to be invoked indirectly by using a reference to the function. A delegate declaration defines a class that is derived from the class System.Delegate. A delegate instance encapsulates one or more methods, each of which is referred to as a callable entity. For instance methods, a callable entity consists of an instance and a method on that instance. For static methods, a callable entity consists of just a method. Given a delegate instance and an appropriate set of arguments, one can invoke all instance methods of that delegate with that set of arguments. Consider the following example of a delegate:

    class Test { static void F() { System.Console.WriteLine("Test.F"); }

  • static void Main() { SimpleDelegate dele = new SimpleDelegate(F); dele(); } }

    The above example creates a SimpleDelegate instance, dele, and then immediately calls it. This program displays Test.F. 13. Write a program to demonstrate the usage of enums in C#. Ans. The following program illustrates the use of enums.

    enum Color { Red, Blue, Green } class Shape { public void Fill(Color color) { switch(color) { case Color.Red: Console.WriteLine(RED); break; case Color.Blue: Console.WriteLine(BLUE); break; case Color.Green: Console.WriteLine(GREEN); break; default: break; } Console.Read(); } }

    The above program shows a color enum and a method that uses this enum. 14. Write a note on namespaces in C#.

    Ans. C# programs are organized by using namespaces. Namespaces are used both as an internal organization system for a program, and as an external organization system. This is a way of writing program elements that are exposed to other programs. A namespace declaration consists of the keyword namespace, followed by a namespace name and body:

    namespace NamespaceName { ... // namespace body }

  • Classes actually contain data and Namespaces are used to logically arrange classes. Namespaces can also contain many other Namespaces and classes. C# classes are organized by using namespaces. Namespaces provide a way to group classes by providing an extra level of naming beyond the class name. Namespaces are implicitly public and the declaration of a namespace does not include any access modifiers. The identifier or name of a namespace may be a single identifier or a sequence of identifiers separated by . tokens. The latter form permits a program to define a nested namespace. Consider the following code snippet: namespace Example.Namespace1 { public class NmEx { public string Display() { return "Namespace example"; } } } Namespaces are hierarchical, and the name Example.Namespace1 is an easier and convenient way for defining a namespace named Example that contains a namespace named Namespace1, as in: namespace Example { namespace Namespace1 { } } 15. What is the use of attributes in C# programs? Ans. C# is an imperative language, but like all imperative languages it does have some declarative elements. For example, the accessibility of a method in a class is specified by declaring it public, protected, internal, protected internal, or private. C# generalizes this capability, 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. Programs specify this additional declarative information by defining and using attributes.

    FAQs 1. What will be the value of i in the following code:

    for(int i = 0; i < 10 ; i++); Ans: The variable i will be initialized to 0, then i will be incremented till its value is less then 10. At the end of the loop, i will have a value of 10.

  • 2. What is wrong with the following statement: if(x=5)

    Ans: = is an assignment operator. While checking for values, the comparison operator, ==, has to be used. 3. What will be the output of the following code:

    using System; namespace ConsoleApplication1 { class increment { static void Main() { int x, y, z; x=5; y=++x; z=x++; Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); Console.Read(); } } }

    Ans: 7 6 6 4. Consider the following code:

    string s= Example; char s1= s[2];

    What is the value of s1? Ans: a 5. When do you use a for loop, a while loop, and a do...while loop? Ans: Use a for loop if you know the number of iterations previously. Use the do...while loop when you want the iteration to occur at least once. A while loop is used when the condition has to be first tested.

  • Solutions to Chapter Five Questions 1. Write a note on classes in C#. Ans. A class is a collection of variables and methods. The class defines all the common properties of the different objects that belong to it. Class declarations are reference types. A class can inherit from another class and can implement interfaces. Class members can include constants, fields, methods, properties, events, indexers, operators, instance constructors, destructors, static constructors, and nested type declarations. Each member has an associated accessibility, which controls the portion of the program code that is able to access the member. There are five forms of accessibility. These are as follows: Public, which is selected by including a public modifier in the member declaration. The

    intuitive meaning of public is access not limited. Protected internal (meaning protected or internal), which is selected by including both a

    protected and an internal modifier in the member declaration. The intuitive meaning of protected internal is access limited to this program or types derived from the containing class.

    Protected, which is selected by including a protected modifier in the member declaration. The intuitive meaning of protected is access limited to the containing class or types derived from the containing class.

    Internal, which is selected by including an internal modifier in the member declaration. The intuitive meaning of internal is access limited to the program.

    Private, which is selected by including a private modifier in the member declaration. The intuitive meaning of private is access limited to the containing type.

    2. What are constant members? Give an example. Ans. A constant is a class member that represents a constant value. Constant members are initialized at the time of their declaration. Consider the following example:

    class Constants { public const int A = 1; public const int B = A + 1; }

    The above example shows a class named Constants that has two public constants. 3. Give an example of field member. Ans. Consider the following code, which displays a class and its field members:

    class Color { internal ushort redPart; internal ushort bluePart; internal ushort greenPart; public Color(ushort red, ushort blue, ushort green) { redPart = red; bluePart = blue; greenPart = green;

  • } public static readonly Color Red = new Color(0xFF, 0, 0); public static readonly Color Blue = new Color(0, 0xFF, 0); public static readonly Color Green = new Color(0, 0, 0xFF); public static readonly Color White = new Color(0xFF, 0xFF, 0xFF); }

    In the above example, the Color class has the fields: redPart, bluePart, greenPart, Red, Blue, Green, and White. 4. With appropriate examples, explain parameter passing in C#. Ans. Parameters can be passed by value or by reference. These are explained as follows: Passing by value: The parameter modifiers 'ref' and 'out' relate to how the parameter is

    passed into the method. By default, parameters are passed by value. In this case, when the method is called, the value given is copied to the variable specified in the method declaration. The following example illustrates this point; note that the change made to variable b in the body of the 'change' method does not result in a change to the variable a used to invoke the method. Consider the following code snippet: public static void Main() {

    int a = 0; change(a); Console.WriteLine(a); //Line 2 } public static void change(int b) { b = 5; Console.WriteLine(b); //Line 1 } In the above example, the value of a is initialized to 0. When the change method is called, the value of a is changed to 5. Therefore, Line1 displays 5. However, the parameter a is passed by value. Therefore the original value of a does not change. Therefore, Line2 would display 0.

    Passing by reference: In C#, you can pass variables into methods 'by reference'. When a variable is passed by reference, the 'ref' modifier must be used both in the method definition argument list and the method invocation.

    Consider the following example: public static void Main() { int a = 0; change(ref a); Console.WriteLine(a); //Line2 } public static void change (ref int b) { b = 5; Console.WriteLine(b); //Line1 }

    In the above example, the value of a is initialized to 0. When the change method is called, the value of a is changed to 5. Therefore, Line1 displays 5. Here, the parameter a is passed by reference. Therefore the original value of a changes. Therefore, Line2 would display 5.

  • 5. What is the use of property member in a class? Ans. A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a Window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the block of statements to be executed when their values are read or written.

    6. What are events? Give an example to demonstrate its usage. Ans. An event is a set of actions that is triggered to call a function or to start an operation. A class defines an event by providing an event declaration and an optional set of event accessors. The declaration resembles a field declaration, with an added event keyword. The type of this declaration must be a delegate type. Consider the following example:

    void Button1_Click(object sender, EventArgs e) { MessageBox.Show("Button1 was clicked!"); }

    In the above example, a click event is raised when Button1 is clicked. 7. With an example, explain indexers. Ans. An indexer enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access. Indexer declarations are similar to property declarations, with the main differences being that indexers are nameless and that indexers include indexing parameters. The indexing parameters are provided between square brackets. Consider the following example:

    using System; public class Stack { private Node GetNode(int index) { Node temp = first; while (index > 0) { temp = temp.Next; index--; } return temp; } public object this[int index] { get { if (!ValidIndex(index)) throw new Exception("Index out of range.");

  • else return GetNode(index).Value; } set { if (!ValidIndex(index)) throw new Exception("Index out of range."); else GetNode(index).Value = value; } } ... } class Test { static void Main() { Stack s = new Stack(); s.Push(1); s.Push(2); s.Push(3); s[0] = 33; // Changes the top item from 3 to 33 s[1] = 22; // Changes the middle item from 2 to 22 s[2] = 11; // Changes the bottom item from 1 to 11 } }

    The above example shows an indexer for the Stack class. 8. Explain each of the following with an example: a. Instance constructors Ans. An instance constructor is a member that implements the actions required to initialize an instance of a class. Consider the following example:

    using System; class Point { public double x, y; // Instance constructor public Point() { this.x = 0; this.y = 0; } //Parameterized Instance constructor public Point(double x, double y) { this.x = x; this.y = y; } public static double Distance(Point a, Point b) { double xdiff = a.x - b.x;

  • double ydiff = a.y - b.y; return Math.Sqrt(xdiff * xdiff + ydiff * ydiff); } public override string ToString() { return string.Format("({0}, {1})", x, y); } } class Test { static void Main() { Point a = new Point(); Point b = new Point(3, 4); double d = Point.Distance(a, b); Console.WriteLine("Distance from {0} to {1} is {2}", a, b, d); } }

    The above example shows a Point class provides two public instance constructors, one of which takes no arguments, while the other takes two arguments.

    b. Destructor Ans. A destructor is a member that implements the actions required to destroy an instance of a class. Destructors cannot have parameters, they cannot have accessibility modifiers, and they cannot be called explicitly. The destructor of an instance is called automatically during garbage collection. Consider the example:

    using System; class Point { public double x, y; public Point(double x, double y) { this.x = x; this.y = y; } ~Point() { Console.WriteLine("Destructed {0}", this); } public override string ToString() { return string.Format("({0}, {1})", x, y); } }

    The above example shows a Point class with a destructor. c. Static constructor Ans. A static constructor is a member that implements the actions required to initialize a class. Static constructors cannot have parameters, they cannot have accessibility modifiers, and they cannot be called explicitly. The static constructor for a class is called automatically.

  • Consider the following code snippet: class Employee { private static DataSet ds; static Employee() { ds = new DataSet(...); } public string Name; public decimal Salary; ... }

    The above example shows an Employee class with a static constructor that initializes a static field. 9. How does C# support inheritance? Ans. C# classes support inheritance by using the : operator. Consider the following example:

    using System; class A { public void F() { Console.WriteLine("Inside A.F"); } } class B: A { public void G() { Console.WriteLine("Inside B.G"); } } class Test { static void Main() { B b = new B(); b.F(); // Inherited from A b.G(); // Introduced in B A a = b; // Treat a B as an A a.F(); } }

    The output will be: Inside A.F Inside B.G Inside A.F The above program shows a class B that derives from A. The class B inherits A's F method, and introduces a G method of its own. 10. What is method overloading? Give an example.

  • Ans. Method overloading refers to the methods with the same name but different signatures doing different tasks. Consider the following example:

    using System; class PolymorphismEx { public static int add(int a, int b) { int sum=a+b; Console.WriteLine(sum); } public static int add(int a, int b, int c) {

    int sum=a+b+c; Console.WriteLine(sum); } static void main() {

    add(3,4); add(3,4,5); add(5,6);

    } }

    In the above example, the add function is overloaded as the two add functions have different signatures. The output of the above program is: 7 12 11 11. What is operator overloading? Give an example. Ans. Operator overloading refers to loading an operator to perform different operations on different data types on different contexts. To overload an operator in a class, one defines a method by using the 'operator' keyword. The following program uses operator overloading to create a complex number class ComplexAdd that defines complex addition. The program displays the imaginary and the real parts of the numbers and the addition result using an override of the ToString method.

    // complexAdd.cs using System; public struct ComplexAdd { public int r; public int img; public Complex(int r, int img) { this.r = r; this.img = img; } // Declare which operator to overload

  • public static ComplexAdd operator +(ComplexAdd c1, ComplexAdd c2) { return new ComplexAdd(c1.r + c2.r, c1.img + c2.img); } // Override the ToString method to display a complex number in a required format: public override string ToString() { return(String.Format("{0} + {1}i", r, img)); } public static void Main() { ComplexAdd var1 = new ComplexAdd(5,3); Complex var2 = new Complex(6,2); // Add two Complex objects (var1 and var2) through the // overloaded plus operator: ComplexAdd total = var1 + var2; // Print the numbers and the sum using the overridden ToString method: Console.WriteLine("First complex number: {0}",var1); Console.WriteLine("Second complex number: {0}",var2); Console.WriteLine("The sum of the two numbers: {0}",total); } }

    Output First complex number: 5 + 3i Second complex number: 6 + 2i The sum of the two numbers: 11 + 5i FAQs 1. What is constructor chaining? Ans: Constructor chaining refers to one constructor being called by another constructor. Consider the following code snippet: class ConstrCh { private ConstrCh () { Console.Write("1"); } private ConstrCh (int x):this() { Console.Write("2"); } public ConstrCh (int x, int y):this(10) { Console.Write("3"); } } class Display { public static void Main() {

  • ConstrCh c = new ConstrCh (10,20); // Displays 123 } } In the above program the ConstrCh (int x, int y) invokes the ConstrCh (int x) constructor by using a special syntax : this(arguments), which in turn invokes the ConstrCh () constructor. 2. How would you implement encapsulation in classes? Ans: Access specifiers are used to implement encapsulation in classes. For example, if we want to make a member variable to be inaccessible from outside the class, we need to declare it private. 3. Does C# support multiple inheritance? Ans: C# does not support multiple inheritance. However, C# supports multiple interfaces. 4. How do you declare a pure virtual function in C#? Ans: You can declare a pure virtual function in C# by using the abstract modifier. Consider the following example:

    public abstract void func(int i); Here, the func method is a pure virtual function.

  • Solutions to Chapter Six Questions 1. What is a preprocessor? Explain the purpose of the following directives: #if #else #elif #endif #define #undef #warning #error #line Ans. A preprocessor manipulates the source code. It breaks up the source code into modules. Preprocessor directives instruct the preprocessor to perform specific tasks. Some of the preprocessor directives are explained below. #if: It begins a conditional directive for testing a symbol, to see if they evaluate to true. If true, the compiler evaluates all the code between the #if and the next corresponding directive. #else: It evaluates if none of the expressions in the preceding #if or #elif directives evaluate to true. #elif: It evaluates if neither the preceding #if nor any preceding #elif directive expressions evaluate to true. #endif: It specifies the end of an #if directive. #define: It defines a symbol, which can be passed to the #if directive to evaluate the expression as true. Consider the following code, which illustrates the use of #if, #else, #elif, #endif, and #define:

    #define DEBUG #define VC_V6 using System; public class IfClass { public static void Main() { #if (DEBUG && !VC_V6) Console.WriteLine("DEBUG has been defined"); #elif (!DEBUG && VC_V6) Console.WriteLine("VC_V6 has been defined"); #elif (DEBUG && VC_V6) Console.WriteLine("DEBUG and VC_V6 has been defined"); #else Console.WriteLine("DEBUG and VC_V6 has not been defined"); #endif } }

    Output DEBUG and VC_V6 has been defined. #undef: It undefines a symbol. Consider the following code:

    #undef DEBUG

  • using System; public class Test { public static void Main() { #if DEBUG Console.WriteLine("DEBUG has been defined"); #else Console.WriteLine("DEBUG has not been defined"); #endif } }

    Output DEBUG has not been defined. #warning: It generates a Level 1 warning from a specific location in the code. Consider the following code snippet:

    #define DEBUG public class Test { public static void Main() { #if DEBUG #warning DEBUG defined #endif } }

    #error: It generates an error from a specific location in the code. Consider the following code snippet:

    #define DEBUG public class Test { public static void Main() { #if DEBUG #error DEBUG defined #endif } }

    #line: It changes the compiler's line number and the file name. Consider the following code snippet:

    public class Test { public static void Main() { #line 100 int i; // error or warning will be: CS0168 on line 100 #line 10 char c; // error or warning will be: CS0168 on line 10 } }

    2. What is an exception? How are exceptions handled in C#? Ans. An exception is any error condition or unexpected behavior encountered by a program in execution. Exceptions can be raised because of: Fault in the code or in shared library.

  • Unavailability of operating system resources. Unexpected conditions encountered by the CLR encounters. Exceptions are handled by a try statement. When an exception occurs, the system searches for the nearest catch block that can handle the exception. Once a matching catch block is found, the control is transferred to the first statement of the catch block and the catch block executes. If no matching catch block or finally block is found, then the execution of the thread is terminated. Note: If the application does not handle these exceptions, then the application terminates (default behavior). 3. What is an unsafe code? Explain. Ans. Unsafe code refers to the code that is processed with low security levels. There are situations where access to pointer types becomes a necessity. For example, interfacing with the underlying operating system, accessing a memory-mapped device, or implementing a time-critical algorithm may not be possible without access to pointers. To address this need, C# provides the ability to write unsafe code. In unsafe code, it is possible to declare and operate on pointers, to perform conversions between pointers and integral types, to take the address of variables, and so forth. In a sense, it is like writing C code within a C# program. Unsafe code must be clearly marked with the modifier unsafe, so developers cannot possibly use unsafe features accidentally. When CLR finds this unsafe modifier, the execution engine works to ensure that the unsafe code cannot be executed in an untrusted environment. 4. What is threading? List out the advantages and disadvantages of multiple threads. Ans. Threads are the basic unit to which an operating system allocates processor time, and more than one thread can run inside that process. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to save the thread context until it is scheduled. The thread context includes all of the information the thread needs to resume execution, including the set of CPU registers and stack, in the address space of the thread's host process. Multithreading offers the following advantages: Improved responsiveness: If the application is performing operations that take a

    perceivably long time to complete, these operations can be put into a separate thread which will allow the application to continue to be responsive to the user.

    Faster application: Multiple threads can lead to improved application performance. For example, if there are a number of calculations to be performed, then there the application can be made faster by performing multiple operations at the same time.

    Prioritization: Threads can be assigned a priority which would allow higher priority tasks to take precedence over lower priority tasks.

    Multithreading has the following disadvantages: Programming and debugging is more complex: With multithreaded applications the

    programmer must ensure deadlock avoidance. Threads add overhead to the system: In order for the operating system to track a large

    number of threads it is going to consume processor time. If there are too many threads then each thread may not be given enough time to execute during its time slice.

    5. Write a note on library base classes. Ans. The .NET Framework base classes include classes, interfaces, and value types that provide access to system functionality. To facilitate interoperability between languages, the .NET Framework base classes are CLS compliant and therefore can be used from any programming language.

  • The .NET Framework library base classes are the foundation on which .NET applications, components, and controls are built. These also include types that perform the following functions: Represent base data types and exceptions Encapsulate data structures Perform I/O operations Access information of data types Perform .NET Framework security checks Provide data access, GUI, and Web services 6. What is the role of System.Object, System.String, System.Array and System.Collections Classes? Ans. The roles of the various classes and namespaces are as follows: The System.Object class provides classes and methods that allow you to build generic

    routines, provides Type System Unification, and enables working with groups collections.

    The System.String class provides methods that allow you to perform various string operations.

    The System.Array class provides methods for creating, traversing, manipulating, sorting, and searching arrays.

    The System.Collections namespace contains interfaces and classes that allow you to define various collections of objects, such as lists, queues, bit arrays, hash tables, and dictionaries.

    7. What are the different methods supported by System.Object class? Give an example for each. Ans. The methods are: Equals: This method of the object class provides a default implementation that compares

    two reference type objects for reference equality. The following code snippet illustrates the use of the Equals method: public static void Main() { string str1= Mark; string str2= Adam; str3= Mark; Console.WriteLine(Object.Equals(str1,str2)); //Displays False Console.WriteLine(Object.Equals(str1,str3)); //Displays True }

    ReferenceEquals: This method compares object instances. The following code snippet illustrates the use of the ReferenceEquals method: public static void Main() { object obj1= null; object obj2= null; Console.WriteLine(Object.ReferenceEquals(obj1,obj2)); //Displays True

  • } ToString: This method returns a string representation of a type.

    The following code snippet illustrates the use of the ToString method: public class Example { void StrConvert() { Object obj= new Object(); Console.WriteLine(obj.ToString()); //Displays System.Object } }

    GetType: This method returns a Type object, describing the object it was called on. The following code snippet illustrates the use of the GetType method: public static void Main() { Class1 obj= new Class1(); Console.WriteLine(obj.GetType()); //Displays Class1 }

    GetHashCode: This method makes any object usable in a hash table or any hashing algorithm. The following code snippet illustrates the use of the GetHashCode method: public struct Int32 { public int val; public override int GetHashCode() { return val; //Returns an integer value } }

    MemberwiseClone: This method is used to create a bitwise copy of the type. The following code snippet illustrates the use of the MemberwiseClone method: public static void Main() { Class1 obj1= new Class1(); obj1.name= Stephen; Class1 obj2 = (Class1)obj1.MemberwiseClone; }

    Finalize: This method is used as a destructor. The Finalize destructor is called after the last reference to an object is released from the memory. The .NET Framework automatically runs the Finalize destructor to destroy objects in the memory. The following code snippet illustrates how to override the Finalize method: ~Object();

    8. What is boxing and unboxing? Explain with an example. Ans.

  • Boxing refers to the conversion of value types to object types. Consider the following code snippet: public static void Main() { int var= 21; object obj=var; //Boxing } In the memory, var and obj are represented in the following manner.

    Representation of var and obj in Memory

    Unboxing refers to the conversion of object types to value types. Consider the following code snippet: public static void Main() { int var= 21; object obj=var; //Boxing int var2= (int)obj; }

    In the memory, var, obj, and var2 are represented in the following manner. Representation of var, obj, and var2 in Memory

    9. Write a program to replace all r by R in the string rose is a rose.

    21

    int21

    Stack Heapvar

    obj

    21

    int21

    21

    Stack Heapvar

    obj

    var2

  • Ans. This program is given below:

    using System; namespace ConsoleApplication1 { class Change { static void Main() { string errString = "rose is a rose"; string correctString = errString.Replace("r", "R"); Console.WriteLine(correctString); Console.ReadLine(); } } }

    10. Write a note on the following: a. Single-dimensional arrays Ans. Single-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 = new int [5]; This array contains the elements from arr[0] to arr[4]. The new operator is used to create the array and initialize the array elements to their default values. In this case, all the array elements are initialized to zero. An array that stores string elements can be declared in the same way. For example:

    string[] myStringArray = new string[6];

    b. Multidimensional arrays Ans. Multidimensional array is defined as an array having more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns:

    int[,] arr = new int[4,2]; The following code creates an array of three dimensions, 4, 2, and 3, as shown below:

    int[,,] arr = new int [4,2,3]; c. Jagged arrays Ans. A jagged array is an array whose elements are arrays. The elements of a jagged array can be 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[][] myJaggedArr = new int[3][]; Before we can use myJaggedArr, its elements must be initialized. We can initialize the elements like:

    myJaggedArr [0] = new int[5];

  • myJaggedArr [1] = new int[4]; myJaggedArr [2] = new int[2];

    Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers. It is also possible to use initializers to fill the array elements with values, in which case we do not need the array size. For example: myJaggedArr [0] = new int[] {1,3,4,7,9}; myJaggedArr [1] = new int[] {0,2,9,6}; myJaggedArr [2] = new int[] {18,22}; A jagged array can be initialized in the following manner as well:

    int[][] myJaggedArr = new int [][] { new int[] {1,3,5,7,9}, new int[] {0,2,4,6}, new int[] {11,22} };

    d. Passing arrays by using ref and out Ans. The ref and out parameters allow you to retain the change in the value of a variable when control passes back to the calling procedure. Without these keywords, the variable would not retain the modified value once the control passes back to the calling procedure. A ref parameter of an array type must be assigned by the caller. Therefore, there is no need to be definitely assigned by the callee. A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array. For example:

    public static void MyMethod(ref int[] arr) { arr = new int[10]; // arr initialized to a different array }

    An out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee.

    For example: public static void MyMethod(out int[] arr) { arr = new int[10]; // definite assignment of arr }

    11. What is the use of System.Collections namespace? Ans. The System.Collections namespace contains interfaces and classes that are used to define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries. FAQs 1. How do you define your own exception classes?

  • Ans: You can define your own exception classes by deriving the exception classes from the System.Exception class. Consider the following code snippet:

    using System; public class NameNotFound: Exception { : }

    In the above code snippet, the NameNotFound exception class is derived from the Exception class. 2. What will be the output of the following code:

    using System; namespace ConsoleApplication1 { class Test { static void Main() { int a=5; int b=5; Console.WriteLine(a==b); Console.WriteLine(a.Equals(b)); string str1 = "abc"; string str2 = "abc"; Console.WriteLine( str1 == str2 ); Console.WriteLine( str1.Equals(str2) ); Console.Read(); } }

    } Ans: True True True True

    3. How do you compare two strings by ignoring their case? Ans: You can do a case-insensitive string comparison by using the String.Compare function. This function takes three parameters. The first two parameters are the strings that are to be compared. The third parameter takes a boolean value, which specifies whether the case is to be ignored or not. Consider the following code snippet:

    String.Compare(abc,ABC,true) //Returns true The above code snippet displays true because the third parameter is set to true. Solutions to Chapter Seven Questions 1. Give the overall concept of ADO.NET with the help of figures.

  • Ans. ActiveX Data Objects for the .NET Framework (ADO.NET) is a set of classes that provide data access services to the .NET programmer. ADO.NET provides a rich set of components for creating distributed, data-sharing applications. It is an integral part of the .NET Framework, providing access to relational database, XML, and application data. ADO.NET supports a variety of development needs, including the creation of front end database clients and middle tier business objects used by applications, tools, languages, or Internet browsers. ADO.NET provides consistent access to data sources such as Microsoft SQL Server, or data sources exposed via OLE DB and XML. Data sharing applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data. The data residing in a database is retrieved through data provider. Different components of the data provider retrieve data from the database, provide the data to the Visual Basic .NET application, and update the database with the changes made in the application. An application can access data either through a dataset or through a DataReader object: Using a dataset: In this case, the data is cached in a dataset and the application accesses

    the data from the dataset. Using a data reader: In this method, a DataReader object, which is a component of the

    data provider, uses the Connection object to connect to the database, uses the Command object to retrieve data, and provides data to the application in a read-only and forward-only mode.

    Refer to pages 120-123 of the SG for diagrams on the ADO.NET architecture. 2. Explain in detail the ADO.NET architecture. Ans. The ADO.NET components have been designed for easy access and manipulation of data. There are two central components of ADO.NET, DataSet and .NET Data Provider. The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET. The DataSet is explicitly designed for data access independent of any data source. It can be used with multiple and different data sources, used with XML data, or used to manage data local to the application. The DataSet contains a collection of one or more DataTable objects. The other core element of the ADO.NET architecture is the .NET Data Provider, whose components (Connection, Command, DataReader, and DataAdapter) are explicitly designed for data manipulation. The Connection object provides connectivity to a data source. The Command object enables access to database commands to return data, modify data, run stored procedures, and so on. The DataReader provides a high-performance stream of data from the data source. Finally, the DataAdapter provides the bridge between the DataSet object and the data source. The DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet with data, and to update changes made to the data in the DataSet back to the data source.

    3. What is a data provider? Explain. Ans. A data provider is used for connecting to a database, retrieving data, storing the data in a dataset, reading the retrieved data, and updating the database. There are two types of data providers:

  • OLE DB data provider: This type of data provider works with all the OLE DB providers, such as SQL OLE DB provider, Oracle OLE DB provider, and Jet OLE DB provider. The OLE DB Data provider classes are present in the System.Data.OleDb namespace.

    SQL Server data provider: This type of data provider is used to work specifically with Microsoft SQL Server. A SQL Server data provider is recommended for working with a Microsoft SQL Server data source, because a SQL Server data provider allows fast access to a data source without going through an OLE DB or ODBC layer. The SQL Server data provider classes are present in the System.Data.SqlClient namespace.

    4. What is a dataset? Explain. Ans. A dataset is a cached set of database records. ADO.NET is based on a disconnected data structure, therefore it is not possible for the application to interact with the database for processing each record. Therefore, the data is retrieved and stored in datasets. A dataset is the most common method of accessing data as it implements a disconnected architecture. You can work with the records stored in a dataset as you work with real data; the only difference being that the dataset is independent of data source and you remain disconnected from the data source. ADO.NET supports scalability by working with datasets. Database operations are performed on the dataset instead of on the database. As a result, resources are saved, and the database can meet the increasing demands of users more efficiently. The dataset acts like a virtual database containing tables, rows, and columns. An application works with the database records stored in the dataset.

    5. Write a program to show the demonstration of ADO.NET. Ans. The following program demonstrates the use of ADO.NET. Write the following code in the Click event of a button named Delete:

    Private Sub Delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim result As Integer Dim conn As New OleDb.OleDbConnection("Provider=SQLOLEDB;User ID=sa;Password=;Trusted_Connection=yes;Initial Catalog=CallCenter11;data source=localhost") conn.Open() Dim deleteEMP As OleDb.OleDbCommand = New OleDb.OleDbCommand("delete from Employees where EmpID='E003'", conn) result = deleteEMP.ExecuteNonQuery() End Sub

    In the code given for the Click event of the Delete button, a connection object conn is created by providing the information about the provider, the data source server, database name that is to be accessed, and the ID and password for connecting to the data source. Then, the connection with the database is opened and a DataCommand object deleteEMP is created from the OleDbCommand class. The DataCommand object deleteEMP is initialized by setting the SQL statement to be executed using the Connection object conn. Then, the command is executed and the number of rows affected by the execution of the command is stored in an integer result.

  • FAQs 1. What is the difference between a typed and an untyped dataset? Ans: Typed and untyped dataset are compared in the following table.

    Typed Dataset Untyped Dataset

    It has an associated XML schema, which is created at the time of the creation of the dataset. The XML schema contains information about the dataset structure such as the tables, columns, and rows.

    It does not have any associated XML schema.

    In a typed dataset, the dataset structure is stored in an XML format.

    In an untyped dataset, the tables and columns are represented as collections.

    The structure of a typed dataset is decided at the time of its creation.

    The structure of an untyped dataset is not known during compilation.

    Typed Dataset Vs. Untyped Dataset 2. What is data binding? How many types of data binding are there? Ans: After the data is retrieved from the database, it has to be bound to a control on a Windows Form to be displayed in a customized format. Such a binding is termed as data binding. Data binding is of two types: Simple data binding: It is the process of binding a control, such as a text box or a label,

    to a value in a dataset. The dataset value can be bound to the control by using the properties of the control. For example, you can bind the value of the Name column in the dataset to a TextBox control by setting the Text property under the DataBindings category of the TextBox control.

    Complex data binding: It is the process of binding a component, such as a DataGrid or a ListBox control, to display multiple values for a column from the dataset rows.

    3. Give any two new features of ADO.NET 2.0. Ans: Some of the new features of ADO.NET 2.0 are: Multiple Active Result Sets (MARS): In the earlier versions of SQL Server, database

    applications could not maintain multiple active statements on a connection. When using SQL Server default result sets, the applications had to process or cancel all result sets from one batch before it could execute any other batch on that connection. MARS is a new feature supported by Visual Studio 2005 that allows you to: Implement multiple batches on a single connection. Have more than one pending request under a given SQL Server connection.

    Batch updates: In the earlier versions of ADO.NET, a DataAdapter could send only one SQL statement at a time to the server. This hindered faster updates to the database. To address this issue, ADO.NET 2.0 now supports batch updates. Batch support in ADO.NET 2.0 allows a DataAdapter to group insert, update, or delete operations from a DataSet or DataTable to the server, instead of sending one operation at a time. A significant benefit of batch updates is that there are fewer round trips to the database server if you have a large number of rows to update. Batch updates are supported for the .NET data providers for SQL Server (SqlClient) and Oracle (OracleClient).

    4. When should you select a dataset and a data reader? Ans:

  • When you need to work with a large number of tables, you should use a data reader. If the number of tables is less, you should use a dataset. If multiple users use the database and the database needs to be updated frequently, you should use a data reader.

    Solutions to Chapter Eight Questions 1. What is a Web service? Explain its working. Ans. Web service refers to a platform on which you can build distributed applications. A Web service exposes a number of methods that provide functionality that can be used by one or more applications, regardless of the programming languages, operating systems, and hardware platforms used to develop them. In other words, a Web service

    ensures interoperability. Consider the following figure. Communication Between Client Application and Web Service

    The functionality exposed by a Web service can be accessed by applications by using Internet standards, such as Simple Object Access Protocol (SOAP). SOAP is a protocol that uses extensible Markup Language (XML) to describe data and HyperText Transfer Protocol (HTTP) to transmit application data. An application that uses a Web service is called a Web service client. The client sends a request to the Web service. The cloud in the figure refers to the Internet. If the Web service calls some other service to get the answer or response, the Web service can take a while to respond. While it is waiting for the response, the client can perform other operations. 2. How is a Web service different from a Web page? Ans. The differences between a Web service and a Web page are listed in the following table.

    Web Services Web Page

    No User Interface Has a User Interface

    Interacts with application Interacts with the user

    Works with any type of client Works with web browser client

    Web Services Vs. Web Page

    Client Application

    Web Service

    Request

    Response

  • 3. With a neat diagram, explain the event handling process of Web forms. Ans. Consider a Web form with a button. If a user clicks the button control, an event Click is raised for the button on the client computer. However, the browser does not process the event. Instead, the browser raises a postback event so that the Web server is alerted about the Click event being raised. Next, the event handler written for the Click event is processed on the Web server and the output is sent to the client computer. 4. What is ASP.NET? Ans. ASP.NET is a framework for developing high performance Web applications. It is a compiled, .NET-based environment. You can write applications in any .NET compatible language, including VB.NET, C#, and JScript .NET. Additionally, the entire .NET Framework is available to any ASP.NET application 5. What is the use of ASP.NET? Ans. ASP.NET provides a new programming model and infrastructure for more secure, scalable, and stable applications. You can write applications in any .NET compatible language, including VB.NET, C#, and JScript .NET. Developers can easily use the benefits of these technologies, which include the managed CLR environment, type safety, inheritance, and so on. ASP.NET has been designed to work seamlessly with What You See Is What You Get (WYSIWYG) HTML editors and other programming tools, including Microsoft Visual Studio .NET. Not only it makes Web development easier, but it also provides all the benefits that tools offer, including a GUI that developers can use to drop server controls onto a Web page and fully integrated debugging support. 6. Write a program to display Welcome to ASP.NET 8 times in increasing order of their font size by using ASP.NET. by using ASP.NET. Ans. The following program displays Welcome to ASP.NET eight times in increasing order of their font size. In the following code, the Web application name WebApplication9 is application specific:

    WebForm1 Welcome to ASP.NET ASHISH

  • 7. What is the role of System.Web? Ans. The System.Web namespace supplies classes and interfaces that enable browser and server communication. This namespace includes the