CHAPTER-1 (Introduction to .NET)
1. What is .NET?
Answer-
The .NET is
2. What is .Net Framework?
Answer-
The .NET Framework is a technology that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the following objectives:
3. What is .Net technology? Describe briefly its origins.
Answer-
Microsoft's .NET technology is a technology intended to connect. What to connect? Well the whole thing that can be linked through software - people, structures, computers, and extra things as well as devices.
A further thorough explanation of .NET would be to it is a top rank domain, at the start designed to be used by Internet Service Providers (ISP), but now it has extended and everybody can create use of a .net domain. It uses the Internet domain Naming System (DNS) and it is a contraction of the word 'Network'.
NET depends on four Internet standards:
Microsoft views this new technology as revolutionary, enabling Internet users to do things that were never before possible, such as integrate fax, e-mail and phone services, centralize data storage and synchronize all of a users computing devices to be automatically updated.
4. What is web service? How it is achieved using .Net strategy?
Answer-
A Web service is a method of communication between two electronic devices over r World Wide Web. A web service is a software function provided at a network address over the web or the cloud; it is a service that is "always on" as in the concept ofutility computing.
5. What is Microsoft Intermediate Language ?
Answer-
Microsoft Intermediate Language is a CPU-independent instruction set.
When you compile a .NET Framework application, it is converted into MSIL.
When you execute the .NET Framework application on a computer, the instructions specified in MSIL are translated into the native code.
MSIL ensure cross-language integration.
Note that MSIL is not interpreted.
6. With what objectives .NET framework is designed. Explain.
Answer-
The .NET Framework is designed to fulfill the following
objectives:
Some Other Objectives of Dot Net Framework:
7. What is Visual Studio.Net ?
Answer-
Visual Studio .NET is just an editor, provided by Microsoft to help developers write .NET programs easily. VS.NET editor
automatically generates lot of code, allows developers to drag and drop controls to a form, provide short
cuts to compile and build the application etc.
8. List the different languages supported by .NET?
Answer-
List of the different languages supported by .NET
C#, VB .Net, j#,C++ .
Cobol,Component Pascal ,Curriculum ,Eiffel ,Forth ,Fortran, Haskell ,Java Language ,Microsoft JScript,Mercury ,Mondrian, Oberon ,Oz ,Pascal, Perl ,Python, RPG ,Scheme, Small Talk, Standard ML,
9. With a neat diagram explain relationship of the common language runtime and the class library to your
application.
Answer-
10. Explain salient features of common language runtime.
Answer-
The Common Language Language Runtime is robust and secure because it includes the following features:
11. Briefly explain what types of applications and services can be developed using .NET framework.
Answer-
--------------------
CHAPTER-2 (Overview of the .NET Framework)
1. What are the components of .NET framework?
Answer-
.Net Framework is a platform that provides tools and technologies to develop Windows, Web and Enterprise applications. It mainly contains two components,
1. Common Language Runtime (CLR)
2. .Net Framework Class Library.
2. What is Common Language Run-time?
Answer-
The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier.
3. Enumerate major services provided by CLR.
Answer-
CLR is a common runtime environment for .NET languages.
The core services of CLR are
4. How does CLR implements C# program?
Answer-
5. What is Common Type System?
Answer-
The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self describing.
6. What is common Language Specification?
Answer-
Common Language Specification is a standard for .net. Common Language Specification is small set of specification to make all languages as a .net compliant languages. cls make a use of cts and clr. if my languages (c#,vb.net,j#,vc++) wants to be compliant language it has to follow cls standard.
7. What is manages code?
Answer-
Managed code is not compiled to machine code but to an intermediate language which is interpreted and executed by some service on a machine and is therefore operating within a (hopefully!) secure framework which handles dangerous things like memory and threads for you. In modern usage this frequently means .NET but does not have to.
8. List some of the important services the Framework Base Classes offer to the user.
Answer-
9. What are the benefits of .Net strategy advanced by Microsoft?
Answer-
The main benefits of t.NET are:
* Makes programming easier thanks to Web services
* Allows the use of different programming languages
* Offers an integrated set of tools for building and integrating Web services
10. Explain the following.
a. MetaData
--metadata is data about data. It is descriptive information about a particular data set, object, or resource, including how it is formatted, and when and by whom it was collected.
b. Cross Language Interoperability
--Language Interoperability means developing one application with more than one language.
Suppose u are developing vb.net application and u need to work with COM components of vb6.0,then it is called language interoperability.
c. Assembliesd.
--Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations.
d.Application Domains
--Application domains provide an isolation boundary for security, reliability, and versioning, and for unloading assemblies. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run.
e. .NET framework class library
The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, thirdparty components can integrate seamlessly with classes in the .NET Framework
f. System Namespace
--The System namespace is the root namespace for fundamental types in the .NET Framework. This namespace includes classes that represent the base data types used by all applications: Object (the root of the inheritance hierarchy), Byte, Char, Array, Int32, String, and so on. Many of these types correspond to the primitive data types that your programming language uses. When you write code using .NET Framework types, you can use your language’s corresponding keyword when a .NET Framework base data type is expect.
11. Briefly explain the different base data type supported by .NET framework
Answer-
Script data type--C++ datatype--.NET Framework class (C# data )
Number int Int32 (int)
Number long Int32 (int)
Number double Double (double)
Number float Single (float)
String BSTR String (string)
Boolean VARIANT_BOOL Boolean (bool)
Object Object Object (object)
--------------------
CHAPTER-3 (Architecture of .NET Framework)
1. With a neat diagram explain the architecture of .NET framework.
Answer-
2. List out the objectives of .Net Framework.
Answer-
The Main Objectives of .NET Framework are-
1) Platform Independent
2) Language Independent
3) Language Interoperability
4) Security
5) Database Connectivity
6) Globalization of Application
Some Other Objectives of Dot Net Framework are:
3. How the windows programming is different from .Net programming?
Answer-
The windows programming is different from .Net programming
-Windows Programming - In Windows Programming the application programs call windows API function directly. The applications run in the windows environment i.e. operating system itself. These types of applications are called unmanaged or unsafe applications.
.NET Programming - In .NET Programming the application programs call .Net Base Class library functions which will communicate with operating system. The applications run in .Net Runtime environment. These types of applications are called as managed or safe applications. The .Net Runtime starts code execution, manages threads, provides services, manages memory etc. The .Net Base classes are fully object-oriented. It provides all functionalities of traditional windows API along with functionalities in new areas like accessing database, internet connections and web services.
4. What are the functionalists of CLR ? Give the steps involved in managed code execution process.Answer-
The CLR has the following functionalists:
The managed execution process includes the following steps:
5. What are assemblies? What are static and dynamic assemblies?Answer-
Assemblies are the basic elements 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.
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 PE files.
Dynamic Assemblies are one which run directly from memory and are not saved to disk before execution. They can be saved to disk after they have executed.
6. How the .Net execution environment with application domain differs from traditional way of execution?
Answer-
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.
7. What is CTS? Explain the classification of types in CTS with a diagram.Answer-
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.
Classification of Types The CTS supports two categories:
* Value Types – It directly stores data in the variable. Value types can be built-in type, user defined types or enumerations.
* Reference Types – It 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.
8. Write a note on metadata.Answer-
Metadata is the key to a simpler programming model, and eliminates the need for Interface Definition Language (IDL) files, header files, or any external method of component reference. Metadata enables .NET Framework languages to describe themselves automatically in a language-neutral manner, unseen by both the developer and the user. Additionally, metadata is extensible through the use of attributes.
Metadata provides the following major benefits:
*Self-describing files.
Common language runtime modules and assemblies are self-describing. A module’s metadata contains everything needed to interact with another module. Metadata automatically provides the functionality of IDL in COM, so you can use one file for both definition and implementation. Runtime modules and assemblies do not even require registration with the operating system. As a result, the descriptions used by the runtime always reflect the actual code in your compiled file, which increases application reliability.
* Language interoperability and easier component-based design.Metadata provides all the information required about compiled code for you to inherit a class from a PE file written in a different language. You can create an instance of any class written in any managed language (any language that targets the common language runtime) without worrying about explicit marshaling or using custom interoperability code.
* Attributes.
The .NET Framework lets you declare specific kinds of metadata, called attributes, in your compiled file. Attributes can be found throughout the .NET Framework and are used to control in more detail how your program behaves at run time. Additionally, you can emit your own custom metadata into .NET Framework files through user-defined custom attributes
9. With a neat diagram explain the architecture of Common Language Runtime.
Answer-
10. Briefly explain the following.
a. Managed Code
-> Managed code is code that has its execution managed by the .NET Framework Common Language Runtime. It refers to a contract of cooperation between natively executing code and the runtime. This contract specifies that at any point of execution, the runtime may stop an executing CPU and retrieve information specific to the current CPU instruction address. Information that must be query-able generally pertains to runtime state, such as register or stack memory contents.
b. Unmanaged Code
-> The code, which is developed outside .NET, Framework is known as unmanaged code.
Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - levefunctions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code.
c. Microsoft Intermediate Language-> It is language independent code. When you compile code that uses the .NET Framework library, you don’t immediately create operating system - specific native code.
Instead, you compile your code into Microsoft Intermediate Language (MSIL) code. The MSIL code is not specific to any operating system or to any language.
d. Just-In-Time Compiler-> Just - in - Time (JIT) compiler, which compiles MSIL into native code that is specific to the OS and machine architecture being targeted. Only at this point can the OS execute the application. The just - in -time part of the name reflects the fact that MSIL code is only compiled as, and when, it is needed.
e. Garbage Collector-> One of the most important features of managed code is the concept of garbage collection. This is the .NET method of making sure that the memory used by an application is freed up completely when the application is no longer in use.
(As CLR is smart to free up the memory, so why Microsoft has given option for pro grammatically calling Garbage collect)
11. Explain the different process of executing the C# code which is written using .NET framework
Answer-
The different process of executing the C# code which is written using .NET framework -
Step 1-Application code is written using a .NET - compatible language C#.
Step 2 -Code is compiled into MSIL, which is stored in an assembly.
Step 3 -When this code is executed (either in its own right if it is an executable or when it is used from other code), it must first be compiled into native code using a JIT compiler.
Step 4 -The native code is executed in the context of the managed CLR, along with any other running applications or processes.
Note: One additional point concerning this process. The C# code that compiles into MSIL in step 2 needn’t be contained in a single file. It’s possible to split application code across multiple source code files, which are then compiled together into a single assembly. This extremely useful process is known as linking.
This is because it is far easier to work with several smaller files than one enormous one. You can separate out logically related code into an individual file so that it can be worked on independently and then practically forgotten about when completed.
--------------------
CHAPTER-4 (Getting started with C# in the .NET framework)
1. With a neat diagram explain the components of .NET framework.
Answer-
2. Explain the important features of .NET.Answer-
The important features of .NET are-
OTHER FEATURES--
*Common Type System -
Language interoperability under .NET is possible only when all the languages share a common data type system. For this, the common type system (CTS) is introduced. CTS ensures that an int in C# is same as an int in VC++. Under CTS, all the classes are derived from the System.Object class and all the primitive data types are mapped to the structures defined in base class library. CTS also specifies the visibility level (from where the type should be accessible) of data types.
*Intermediate Language -
A .NET programming language does not compile into executable code; instead it compiles into an intermediate code called Microsoft Intermediate Language (MSIL). IL is a CPU-independent language. The IL code is sent to the CLR that converts the code to machine language using the Just In Time compiler, which is then run on the host machine. An important aspect of the IL Windows Forms, Web Forms, Web Services, etc.
(Developed in .NET compliant languages) .NET Framework Base Classes (ADO.NET, XML, Threading, I/O, Network) Common Language Runtime (Memory ) Management, Common Type System, Lifecycle Monitoring) 33 language is that it provides the hardware abstraction layer. We can view the IL code of our application using the ILDASM tool shipped with Visual Studio.NET.
*JIT Compilation-
JIT (Just In Time) compiler is a crucial component of the .NET framework. The JIT compiler converts IL code into machine code, which is then executed. The JIT compiler does not compile the entire code at once because it could hamper the performance of the program. It compiles the code at runtime, at the time it is called. The code that is compiled gets stored until the execution comes to an end. This avoids recompilation of code. The reason why conversion from IL code to machine code takes place at runtime is that the JIT first gets information on the processor type and appropriately converts the IL code so that it would run on that type of processor.
* Assemblies-
An assembly is a unit containing IL code of a program. It is similar to a DLL file, but one
difference is that unlike DLL, an assembly is self-describing. Assemblies contain assembly metadata (or manifest) that gives details of the assembly, type metadata describing the types, methods, etc, defined in the assembly and resources.
Garbage Collection Garbage Collection is a program that is invoked by the CLR to free the memory that is not being used by the application. Because of this technique the programmers no more need to take care of memory leakages, dangling pointers and clean up of memory.
That’s it for a brief introduction to the .NET framework. Let us now create a simple program in C# hat uses the .NET framework. It is assumed that you have installed Visual Studio.NET on a machine running under Windows NT/2000/XP
3. Write down the steps to be followed while creating a C# program.Answer-
The steps to create the program are given below.
(a) Start Microsoft Visual Studio.NET from ‘Start | Program | Microsoft Visual Studio.NET’menu option.
(b) Create a new C# project by selecting ‘File | New | Project menu option. A ‘New Project’
dialog would appear. From the ‘New Project dialog box select project type as ‘Visual C#
Projects’.
(c) Select ‘Console Application ’from the list of Templates.
(d) Select a location where this project should get saved. Name the project as Simple. Click the OK button.
(e) A ‘Class1.cs file (cs stands for C Sharp) would get created with the skeleton code given
below:
using System;
namespace Simple
{
class Class1
{
void Main ( string[ ] args )
{
Console.WriteLine ( “Hello C#” );
}
}
}
4. Describe the structure of typical C# program.Answer-
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 skeleton of a C# program that contains all of these elements.
// A skeleton of a C# program
using System; namespace Namespace1
{
class Class1
{
}
struct Struct1
{
}
interface Interface1
{
}
delegate int Delegate1();
enum Enum1
{
}
namespace Namespace2
{
}
class Class2
{
public static void Main(string[] args)
{
}
}
}
5. Why do we use the using directive in a C# program?Answer-
The using directive has two uses:
1. To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:
using System.Text;
2.To create an alias for a namespace or a type. This is called a using alias directive.
using Project = PC.MyCompany.Project;
6. What is the importance of the Main method in a C# program?Answer-
The Main method is the entry point of a C# console application or windows application. When the application is started, the Main method is the first method that is invoked. (The program execution starts from the Main()function. Since C# is a pure object-oriented language it does not allow us to create global variables and fun
7. Why do we use comments in a program?Answer-
Code comments are the "first line" of program documentation. They are used to tell other programmers how your code works, what it's doing, and what they need to know in order to understand it as well as you do.
8. Describe the difference between the two styles of comments used in C#.Answer-
In C# language, the types are divided into two styles of comments:
9. How does the Write() method is different from WriteLine() method?Answer-
The Write () method outputs one or more values to the screen without a new line character.
The WriteLine() always appends a new line character to the end of the string. this means any subsequent output will start on a new line.
tions. Instead, all variables and functions including Main() should be defined inside a class)
10. What is syntax error? How do we detect them?Answer-
These are errors where the compiler finds something wrong with your program, and you can't even try to execute it. For example, you may have incorrect punctuation, or may be trying to use a variable that hasn't been declared.
Syntax errors are the easiest to find and correct. The compiler will tell you where it got into trouble, and its best guess as to what you did wrong. Usually the error is on the exact line indicated by the compiler, or the line just before it; however, if the problem is incorrectly nested braces, the actual error may be at the beginning of the nested block.
11. Write a C# program to display the text “Hello C#”. Explain it.
Answer-
using System;
namespace Simple
{
class Class1
{
static void Main ( string[ ] args )
{
Console.WriteLine ( “Hello C#” );
}
}
--------------------
CHAPTER-5 (C# Language Syntax)
1. With an example explain how to declare variables in C#.Answer-
The following sample shows different ways you can declare a variable:
int a;
int salary, incomeTax, sum;
int count = 10;
string name;
string fullName= “ChandU”;
2. With an example explain the following loop statements in C#.
a. While
Answer-
int i = 0;
while ( i < 5 )
{
Console.WriteLine ( i );
++i;
}
(The above loop repeates 5 times and prints the value of i.
The output of above code would be like this :
0
1
2
3
4)
b. Do..While-
Answer-
int i = 0;
do
{
Console.WriteLine ( i );
i++;
}
while ( i < 5 );
(The above loop is pretty much same as the whileloop. The only difference is, the condition is checked
only after executing the code inside the loop)
c. For-Answer-
for ( int i = 0; i < 5; i++ )
{
Console.Wr iteLine ( i );
}
(The above loop repeats 5 times just like the whileloop and prints the value of i.
The output of above code would be like this :
0
1
2
3
4)
d. Foreach-Answer-
string [ ] names = new string[ ]{ “Abhilash",“Balram”,“ChandU” ,"Sekhar” };
foreach ( string name in names )
{
Console.WriteLine ( name );
}
(foreach loop can be used to iterate through a collection like array,
ArrayList etc.
The above code displays the following output.
Abhilash
Balram
ChandU
Sekhar)
3. With an example explain break and continue statement in C#.Answer-
Break --
‘break’s tatement is used to break out of loops
(‘while’, ‘for’, switch’etc).
string [] names = new string[]{ “Abhilash",“Balram”,“ChandU” ,"Sekhar” };
foreach ( string name in names )
{
Console.WriteLine ( name );
if ( name == “ChandU” )
break;
}
In the above sample, it iterates through the array of 4 items, but when it encounters the name “ChandU”,
it exits the loop and will not continue in the loop anymore.
The output of above sample would be :
Abhilash
Balram
ChandU
Continue-- ‘continue statement is also used to in the loops (‘while’, for, etc). When executed, continue statement will move the execution to the next iteration in the loop, without continuing the lines of code after the ‘continue' ’inside the loop.
string [ ] names = new string[ ]{ “Abhilash",“Balram”,“ChandU” ,"Sekhar” };
foreach ( string name in names )
{
if ( name == “ChandU” )
continue;
Console.WriteLine ( name );
}
In the above sample, when the value of name is “ChandU”, it executes the ‘continue’ which will change the execution to the next iteration, without executing the lines below it. So, it will not print the name, if the name is “ChandU”.
The output of above sample would be :
Abhilash
Balram
Sekhar
4. Write a program to print whether a given number is even or odd.Answer-
Program that finds odd numbers :-
using System;
class Program
{
static void Main()
{
for (int i = 0; i <= 100; i++)
{
if (IsOdd(i))
{
Console.WriteLine(i);
}
}
}
public static bool IsOdd(int value)
{
return value % 2 != 0;
}
}
Output- 1, 3, 5, 7, 9, 11, 13,.................................99
----------
Program that finds even numbers:-
using System;
class Program
{
static void Main()
{
for (int i = 0; i <= 100; i++)
{
if (IsEven(i))
{
Console.WriteLine(i);
}
}
}
public static bool IsEven(int value)
{
return value % 2 == 0;
}
}
Output- 0., 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,......................100.
5. Write a program to print all possible roots of the quadratic equation ax2+bx+c=0.Answer-
6. Write a program to print the factorial of a given number.Answer-
You may write a class called 'Calculator' with a method called 'Factorial()' taking one input parameter and returning the Factorial of the input.
public class Calculator
{
public int Factorial(int a)
{
int factorial = 1;
while ( a > 0 )
{
factorial *= a;
--a;
}
return factorial;
}
}
7. Write a program to print the first n terms of the Fibonacci series.Answer-
using System;
class Program
{
public static int Fibonacci(int n)
{
int a = 0; int b = 1;
for (int i = 0; i < n; i++)
{
int temp = a; a = b; b = temp + b;
}
return a;
}
static void Main()
{
for (int i = 0; i < 15; i++)
{
Console.WriteLine(Fibonacci(i));
}
}
}
Output- 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,.........................n.
8. Write a program to reverse the given number.Answer-
using System;
static class StringHelper
{
public static string ReverseString(string s)
{
char[ ] arr = s.ToCharArray();
Array.Reverse(arr); return new string(arr);
}
}
class Program
{
static void Main()
{
Console.WriteLine(StringHelper.ReverseString("54321"));
Console.WriteLine(StringHelper.ReverseString("98765"));
}
}
Output- 12345, 56789
9. Write a program to find the sum of the digit of a given number.Answer-
using System;
using System.Collections.Generic;
using System.Text;
namespace SumOfDig
{
class Program
{
static void Main(string[] args)
{
long modulo,sum=0;
Console.Write("Enter the Number:");
long number = long.Parse(Console.ReadLine());
while (number > 0)
{
modulo = (number % 10);
sum = sum + modulo;
number = number / 10;
}
Console.WriteLine("The Sum of Digits of number is {0}",sum);
Console.ReadLine();
}
}
}
10. Demonstrate the typical use of goto statement.Answer-
using System;
class Program
{
static void Main()
{
int main()
{
float num,average,sum;
int i,n; printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump;
sum=sum+num;
}
jump: average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
11. Compare and contrast if..else statement and switch statement.
Answer-
They are pretty similar but each has a few special features.
if-else
switch
--------------------
CHAPTER-6 (DataTypes in C#)
1. Briefly explain data types in C# and .NET.Answer-
DataTypes are the basic building block of any language. Microsoft has tried to standardise the datatypes in .NET framework by introducing a limited, fixed set of types that can be used to represent almost anything in programming world.
C++ was very rich in datatypes, but that leads to confusion too. Especially, when you write components that may be consumed by applications written in other platforms, you have to make sure the types used are compatible with other platforms too!
.NET types start from a clean slate. All .NET languages share the same types. So, they are all compatible and no worries.This means, you can call C# code from VB.NET and vice versa, without worrying about type conversions.
.NET data types are either structures or classes, part of the System namespace. For example, the following data types are implemented as struct in .NET:
*Int16
*Int32
*Double
(String is implemented as a class in .NET, for various reasons.)
If you are not very familiar with struct and class, don’t worry about it. You can just use them as if they are simple data types.
Here is how you can declare variables of type Int, Double and String:
*Int16 age, employeeNumber;
* Double salary;
*String name, address;
You can use any of the .NET data types directly in any .NET language - in C#, VB.NET or
xyz.NET.But in addition to the .NET types, each language provides a set of primitive types, which map to the corresponding types in .NET class library. This is why you may see some people use string and some others use String. There is no big difference. string is a primitive data type in C# and String is the corresponding class in .NET class library. The string in C# is mapped to the class in .NET class library. So, whether you use string or String,there is no real difference.
2. List the data types in C# and their corresponding class/struct in .NET class library.Answer-
The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library.
C# Data type Mapped to .NET class/struct
Sbyte Sys tem.SByte
Byte System.Byte
Char System.Char
Float System.Single
Decimal System.Decimal
Double System.Double
Ushort System.UInt16
Short System.Int16
Uint System.UInt32
Int System.Int32
Ulong System.UInt64
Long System.Int64
Bool System.Boolean
String System.String
Object System.Object
3. What is a literal?Answer-
A literal is some data that's presented directly in the code, rather than indirectly through a variable or function call.
(A literal is a value that is expressed as itself. For example, the number 25 or the string "Hello World" are both literals. )
4. What is a constant?Answer-
A constant is a value that never changes. The other type of values that programs use is variables, symbols that can represent different values throughout the course of a program.
A constant can be
a number, like 25 or 3.6
5. What is variable?Answer-
In programming, a variable is a value that can change, depending on conditions or on information passed to the program. Typically, a program consists of instruction s that tell the computer what to do and data that the program uses when it is running.
6. There are thirteen simple value types. List Them.
Answer-
Thirteen simple value types
1.SByte
2.byte
3.char
4.ULong
5.long
6.UInteger
7.int
8.double
9.short
10.UShort
11.float
12.bool
13.decimal
7. List the two different reference types.Answer-
Variables of reference types store references to the actual data. This section introduces the following keywords used to declare reference types:
1.class
2.interface
8. Differentiate between value types and reference data types in C#
Answer-
The differences between values types and reference types :-
1)value types allocated on stack but reference types allocated on heap.
2). A value type variable contains the data itself but reference type variable contains the
address of memory location where data is actually stored.
3). When you copy a value type variable to another one, the actual data is copied and each variable can be independently manipulated but when copying a reference type variable to another variable, only the memory address is copied. Both variables will still point to thesame memory location, which means, if you change one variable, the value will be changed for the other variable too.
4). Integer, float, boolean, double etc are value types and string and object are reference types.
5). Struct is value type but classes and interfaces are reference type
--------------------
CHAPTER-7 (Classes and Object model in .NET)
1. With an example explain class and methods.Answer-
In modern object oriented programming, large computer programs are divided into several ‘classes’. Typically, a large project will have several hundred classes. A class represents an entity in a program.
For example, if you are doing a small program called calculator, you will typically have a single (or more) class called ‘Calculator’(you can give any name for your class). The class will have several ‘methods’, that will do the functionality of the class.
So, your calculator may have methods like the following:
Add()
Subtract()
Multiply()
Divide()
A sample calculator class, written in C# is given below:
using System;
public class Calculator
{
public int Add(int value1, int value2)
{
return value1 + value2;
}
public int Subtract(int value1, int value2)
{
return value1 - value2;
}
public int Multiply(int value1, int value2)
{
return value1 * value2;
}
public int Divide(int value1, int value2)
{
return value1 / value2;
}
}
2. With an example explain get and set properties in a class.Answer-
public class Car
{
private string color;
public Car()
{
}
public string Color
{
get
{
if ( color == “” )
return “GREEN”;
else
return color;
}
set
{
if ( value == “” )
thrown new Exception (“Wrong value.”);
else
color = value;
}
}
}
3. How do we invoke a method in C#?Answer-
using System;
using System.Reflection;
class Program
{
public void Win()
{
Console.WriteLine("{You're a winner}");
}
public void Lose()
{
}
public void Draw()
{
} static void Main()
{
Program p = new Program();
MethodInfo [ ] methods = type of(Program).GetMethods();
foreach (MethodInfo info in methods)
{
Console.WriteLine(info.Name);
if (info.Name == "Win")
{
info.Invoke(program, null);
}
}
}
}
4. What is nesting of methods? Give an example of typical use of methods nesting?Answer-
A type defined within a class or struct is called a nested type. For example:
5. Describe three different ways of providing values to instance variables of a class?Answer-
6. Describe two ways of accessing the values of data fields? Compare them.Answer-
7. What is property? Why are they referred as smart fields?Answer-
8. List at least three important features of properties.Answer-
9. Create a class to hold two integer values. Design a method swap that would take two integer object as parameters and swap their contents.
Answer-
10. What do you mean by name spaces. List the name spaces available in .NET class library.
--------------------
CHAPTER-8 (WinForms)
1. Write a note on the following.
a. Winform-
WinForms is the most commonly used feature of .NET.
'Windows' based applications in .NET is called 'WinForms'. The .NET framework comes with a good number of classes to support 'Form' based application development.
A WinForm application will have atleast one ‘Form’(window), which would be used for the interaction
between the application and user. A Form can contain other controls like TextBox, Label, Button etc.
Large WinForms applications will have several ‘Forms’, some of them used to capture data from user and
some of them used to display data to user. By performing certain actions in each form, user can navigate
to other ‘Forms’in the application.
b. Event Driven Programming-
Event Driven programming model is the most commonly used feature in modern programming. In this
model, you will write appropriate code for each event. Examples for events are
Button Click
Mouse Move
Mouse Click
Key Press
In Winforms application, users interact with the application using various actions in the window (likeclicking a button, moving mouse, pressing keys in keyboard etc). These actions will generate various
events. When an event is generated, the code written for that event will be executed.
2. Write the steps to create Winform applications.Answer-
TO CREATE WINFORMS APPLICATIONS:
3. Briefly discuss the various controls available in System.Windows.Froms.Answer-
4. Write a C# program to create and display a window.Answer-
5. Briefly explain the MessageBox class.Answer-
6. Briefly explain the different types of event that can be generated.Answer-
7. With the help of an example program explain how to add button control to the window.Answer-
8. Write a program to display a message box and read the data entered in the text box. Briefly explain.
Answer-
--------------------
CHAPTER-9 (Inheritance)
1. With an example program explain the inheritance concept in C#.Answer-
As with most programming concepts the subject of inheritance in C# is perhaps best illustrated with an
example. In the previous chapter we created a class called BankAccount:
public class BankAccount
{
public string accountName;
public int accountFee;
private int accountBalance;
private int accountNumber;
public int getAccountNumber()
{
return accountNumber;
}
public void setAccountNumber(int newNumber)
{
accountNumber = newNumber;
}
}
This class does a good job of defining characteristics common to any type of bank account, such as
account holder name, account number and current balance. Imagine, however, that our banking program
needs to support a number of specific types of account. For example, the bank might offer its customers
an interest bearing savings account. A savings account will have all the characteristics of our BankAccount
class but would also need a way to store the prevailing interest rate. One option would be to create a
brand new class from the ground up called SavingsAccountwhich duplicates everything we have in our
BankAccountclass, plus extra members needed for a savings account. Another, more efficient method is
to derive a SavingsAccountclass from the BankAccountclass and then add in the extra functionality
into this subclass.
2. What is re-usability of code? How it is achieved in C#?Answer-
3. What are two forms of inheritance? Give your own examples.Answer-
4. Describe the syntax of single inheritance in C#.Answer-
5. Describe improvement characteristics of inheritance.Answer-
6. How does a base class receive its arguments in order to construct its members properly?Answer-
7. When do we declare a class abstract?Answer-
When at least one of the methods in the class is abstract.
The keyword abstract can be used with both classes and methods in C# to declare them as abstract.
The classes, which we can't initialize, are known as abstract classes. They provide only partial implementations. But another class can inherit from an abstract class and can create their instances.
8. State the characteristics of abstract classes.Answer-
The characteristics of abstract classes-
9. What are the characteristics of abstract methods?Answer-
Characteristics of abstract method are:-
10. What is virtual method?
Answer-
A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overriden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overriden in the derived class using the override keyword
11. With an example program explain how to pass arguments to the base class constructors.Answer-
using System;
class Net
{
public string Name { get; set; }
public Net(Perl perl)
{
// Use name from Perl instance.
this.Name = perl.Name;
}
}
class Perl
{
public string Name { get; set; }
public Perl(string name)
{
this.Name = name;
// Pass this instance as a parameter!
Net net = new Net(this);
// The Net instance now has the same name . Console.WriteLine(net.Name);
}
}
class Program
{
static void Main()
{
Perl perl = new Perl("Sam");
}
}
12. Write a note on abstract class.Answer-
Often a base class is not intended to be instantiated and is provided solely for the purpose of providing an outline for subclasses. Such a class is known as an abstract class.
13. Differentiate between abstract and virtual members.
Answer-
- Only abstract classes can have abstract members.
- A non-abstract class that inherits from an abstract class mustoverride its abstract members.
- An abstract method is implicitly virtual.
- An abstract method cannot provide any implementation.
- A class can have a virtual method.
- The virtual method has an implementation. When you inherit from a class that has a virtual method, you can override the virtual method.
--------------------
CHAPTER-10 (Exception Handling)
1. What are compile time errors? Give some examples. How are they detected?Answer-
2. What are run time errors? Give some examples. How are they detected?
3. What is exception? Give some examples.
Answer-
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
Some examples of exception:-
4. Why is it necessary to handle an exception by a special code?
Answer-
5. Describe the tasks involved in handling exceptions.
Answer-
6. How do you define the following.
a) try block--
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.
b) catch block--
In catch we handle exceptions. The try-catch pattern in the C# language provides an alternative flow control. It traps errors in an efficient and clear way. The catch block allows an optional variable.
Multiple catch blocks can be stacked to provide more control. The final one does not require a variable type.
c) finally block--
If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
7. What do you mean by Exceptions? With the help of an example program explain how exception is handled in C#.
Answer-
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.
8. List at least four exceptions that occur in C# programs.
Answer-
9. What happens when a try block is neither followed by a try block nor ny a finally block.
Answer-
10. What is the purpose of using finally block? Give some examples.Answer-
11. When do you consider it necessary to define your own exception classes?Answer-
12. With an example program explain how to throw your own exceptions.Answer-
13. Briefly explain Standard Exceptions.Answer-
14. Write a note on user defined Exceptions.
Answer-
--------------------
CHAPTER-11 (Arrays)
1. What do you mean by arrays? Explain how define and initialize arrays in C#.
Answer-
2. Differentiate between Rectangular arrays and Jagged arrays.
C# supports two types of multidimensional arrays:
Rectangular and Jagged.
A rectangular array is a single array with more than one dimension, with the dimensions’sizes fixed in the array’s declaration. The following code creates a 2 by 3 multi-dimensional array.
A jagged arrays, one can create multidimensional arrays with irregular dimensions. This flexibility
derives from the fact that multidimensional arrays are implemented as arrays of arrays. The following
piece of code demonstrates how one might declare an array made up of a group of 4 and a group of 6
elements:
3. Explain the need for array variables.
Answer-
4. What is a variable size array? How is it different from a rectangular array?Answer-
5. Give an example of typical use of variable size array.Answer-
6. Write a program to add two matrices.Answer-
using System;
using System.Collections.Generic;
using System.Text;
namespace Add_Two_Matrix
{
class Program
{
static void Main(string[] args)
{
int[,] a = {{1, 2, 3 }, { 4, 5, 6 }, { 7,8,9} };
int[,] b ={ { 4, 8, 7 }, { 6,5,4}, {3,2,1 } };
int[,] c = new int[3,3];
int f = c.Length;
int i, m = 0;
int j = 0;
int n = 0;
for ( i = 0;i<3;i++)
{
Console.WriteLine(" ");
for (j = 0; j < 3; j++)
{
Console.Write(" " + a[i, j]);
}
}
Console.Write("\n");
for ( m = 0; m < 3; m++)
{
Console.WriteLine(" ");
for ( n = 0; n < 3; n++)
{
Console.Write(" " + b[m, n]);
}
}
Console.Write("\n");
for (int k = 0; k < 3; k++)
{
Console.WriteLine("");
for (int l = 0; l < 3; l++)
{
Console.Write(a[k, l] + b[k, l] + "\t");
}
}
Console.WriteLine();
Console.ReadLine();
}
}
}
7. Write a program to multiply two matrices.Answer-
The following C# program will take two matrices of 2*2 order in its input and then print the product of them.
using System;
using System.Collections.Generic;
using System.Text;
namespace matrix_muliplication
{
class Program
{
static void Main(string[] args)
{
int i,j,k,l;
int[,] matrix=new int[2,2];
int[,] matri=new int [2,2];
int[,] matr=new int [2,2];
Console.WriteLine("Enter 1st 2*2 matrix: \n");
for (i=0;i<2;++i)
{
Console.WriteLine("Enter "+ (i+1) +"# row: ");
for (j=0;j<2;++j)
{
matrix[i,j]=Int32.Parse( Console.ReadLine());
}
}
Console.WriteLine("\n");
Console.WriteLine("Enter 2nd 2*2 matrix: \n");
for (i=0;i<2;++i)
{
Console.WriteLine("Enter "+(i+1)+" # row: ");
for (j=0;j<2;++j)
matri[i,j]=Int32.Parse(Console.ReadLine());
}
Console.WriteLine();
Console.WriteLine("Matrix muliplication");
for (j=0;j<2;++j)
{
for (i=0;i<2;++i)
{
for (l = 0; l < 2; ++l)
{
matr[i, j] = matr[i, j] + (matrix[i, l]) * (matri[l, j]);
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(matr[i, j] + "\t");
}
Console.WriteLine();
}
}
}
}
8. Write a program to find row sum and column sum of a matrix.Answer-
using System;
using System.Collections.Generic;
using System.Text;
class mat
{
int i, j, m, n;
int[,] a = new int[20, 20];
public void get()
{
Console.WriteLine("Enter Row Value");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Column Value");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Elements one by one");
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
a[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("Given Matrix");
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
Console.Write("\t{0}", a[i, j]);
}
Console.WriteLine();
}
}
public void diag()
{
int d;
d = 0;
if (m == n)
{
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
if (i == j)
{
d = d + a[i, j];
}
}
}
Console.WriteLine("Diagonal Sum= {0}", d);
}
else
{
Console.WriteLine("Can't Perform Diagonal Sum");
}
}
class matsum
{
static void Main(string[] args)
{
mat ma = new mat();
ma.get();
ma.diag();
Console.Read();
}
}
}
OUTPUT-
Enter Row Value : 2
Enter Column Value : 2
Enter Elements One by One : 2, 2
2 ,2
Given Matrix : 2, 2
2 , 2
Diagonal Sum :4
9. Write a program to verify whether a given matrix is identity matrix or not.
Answer-
include<stdio.h>
#include<conio.h>
void main()
{
int mat[5][5];
int n=3,i,j;
clrscr();
printf("\n\n Enter the order: ");
scanf("%d",&n);
printf("\n Enter the matrix\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf(" %d,%d: ",i+1,j+1);
scanf("%d",&mat[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if((i==j && mat[i][j]==1)||(i!=j && mat[i][j]==0))
continue;
else
{
printf("It is not identity matrix \n");
i=j=n;
}
}
}
if(i==j && i==n)
printf("It is identity matrix \n");
getch();
}
--------------------
CHAPTER-12 (C# Collection Classes)
1. What are C# collection classes? Explain briefly.
Answer-
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:
2. How does an array of ArrayList class different from Array class?Answer-
3. When do we decide to use the ArrayList class over the Array class?
Answer-
4. With an example explain how to create List and ArrayList classes in C#.
Answer-
5. With an example explain the following.
a. Adding items to list.
--Once a List object has been created there are a number of methods which may be called to perform tasks on the list. Once such method is the Add()method which, as the name suggests, is used to add items to the list object:
List<string> colorList = new List<string>();
colorList.Add (“Red”);
colorList.Add (“Green”);
colorList.Add (“Yellow”);
colorList.Add (“Purple”);
colorList.Add (“Orange”);
b. Accessing list items.
Individual items in a list may be accessed using the index value of the item (keeping in mind that the first item is index 0, the second index 1 and so on). The index value is placed in square brackets after the list name. For example, to access the second item in the colorListobject:
Console.WriteLine (colorList[1]);
A list item value can similarly be changed using the index combined with the assignment operator. For example, to change the color from Yellow to Ingido:
colorList[2] = “Indigo”;
All the items in a list may be accessed using a foreachloop.
For example-
foreach (string color in colorList)
{
Console.WriteLine ( color );
}
When compiled and executed, the above code will output each of the color strings in the colorList object.
--
c. Removing items from list.
Items may be removed from a list using the Remove()method. This method takes the value of the item to be removed as an argument. For example, to remove the “Red”string from the colorList object:
colorList.Remove(“Red”);
d. Inserting items into a list
--The Insert()method is provided for this specific purpose. Insert()takes two arguments, an integer indicating the index location of the insertion and the item to be inserted at that location. For example, to insert an item at location 2 in our example list:
colorList.Insert(2, “White”);
e. Sorting lists.
--There is no way to tell C# to automatically sort a list as items are added. If the items in a list are required to be always sorted into order the Sort()method should be called after new items are added-
colorList.Sort();
f. Finding items in a list
--A number of methods are provided with the List and ArrayList classes for the purposes of finding items. The most basic method is the Contains()method, which when called on a List or ArrayList object returns trueif the specified item is found in the list, or falseif it is not.
The IndexOf()method returns the index value of a matching item in a list. For example, the following code sample will output the value 2, which is the index position of the “Yellow”string:
List<string> colorList = new List<string>();
colorList.Add (“Red”);
colorList.Add (“Green”);
colorList.Add (“Yellow”);
colorList.Add (“Purple”);
colorList.Add (“Orange”);
Console.WriteLine(colorList.IndexOf(“Yellow”));
If the item is not found in the List a value of -1 is returned by the IndexOf()method.
This technique could be used to replace a specific value with another. For example, without knowing
in advance the index value of the “Yellow”string we can change to “Black”:
colorList[colorList.IndexOf(“Yellow”)] = “Black”;
The LastIndexOf()method returns the index value of the last item in the list to match the specified item. This is particularly useful when a list contains duplicate items.
g. Clearing the list.
--All the items in a list may be removed using the Clear()method:
colorList.Clear();
The Clear()method removes the items from the list and sets the Countproperty to zero. The Capacity property, however, remains unchanged. To remove the capacity of a list follow the Clear()method call with a call to TrimExcess().
--------------------
CHAPTER-13 (Introduction to ADO.NET)
1. Give the overall concept of ADO.NET.
Answer-
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.
2. Explain in detail ADO.NET architecture.
Answer-
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 set? Explain.
Answer-
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.
4. Write a program to show the demonstration of ADO.NET.
Answer-
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 Intege
Dim conn As New OleDb.OleDbConnection ("Provider=SQLOLEDB;User ID=sa;Password=sql2008;Trusted_Connection=yes;Initial Catalog=CallCenter11;data source=localhost")
con n.Open()
Dim deleteEMP As OleDb.OleDbCommand = New OleDb.OleDbCommand("delete from Employees where EmpID='E003'", con n)
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.
5. What do you mean by ADO.NET data providers? Explain briefly.
Answer-
A .NET data provider is a software library consisting of classes that provide data access services such as connecting to a data source, executing commands at a data source and fetching data from a data source with support to execute commands within transactions. It resides as a lightweight layer between data source and code, providing data access services with increased performance.
The .NET data provider is a component of ADO.NET, a subset of the .NET framework class library.
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.
6. Briefly explain the following ADO.NET objects.
A. the SqlConnectionObject
--To interact with a database, you must have a connection to it. The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the data base. A connection object is used by command objects so they will know which database to execute the command on.
B. the SqlCommandObject
--The process of interacting with a database means that you must specify the actions you want to occur. This is done with a command object. You use a command object to send SQL statements to the database. A command object uses a connection object to figure out which database to communicate with. You can use a command object alone, to execute a command directly, or assign a reference to a command object to an SqlDataAdapter, which holds a set of commands that work on a group of data as
described.
C. the SqlDataReaderObject
--Many data operations require that you only get a stream of data for reading. The data reader object allows you to obtain the results of a SELECT statement from a command object. For performance reasons, the data returned from a data reader is a fast forward-only stream of data. This means that you can only pull the data from the stream in a sequential manner. This is good for speed, but if you need to manipulate data, then a DataSet is a better object to work with.
D. the DataSetObject
--DataSet objects are in-memory representations of data. They contain multiple Datatable objects, which contain columns and rows, just like normal database tables. You can even define relations between tables to create parent-child relationships. The DataSet is specifically designed to help manage data in
memory and to support disconnected operations on data, when such a scenario make sense. The DataSet is an object that is used by all of the Data Providers, which is why it does not have a Data Provider specific prefix.
E. the SqlDataAdapterObject
--Sometimes the data you work with is primarily read-only and you rarely need to make changes to the underlying data source. Some situations also call for caching data in memory to minimize the number of database calls for data that does not change. The data adapter makes it easy for you to accomplish these things by helping to manage data in a disconnected mode. The data adapter fills a DataSet object when reading the data and writes in a single batch when persisting changes back to the database. A data adapter contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the database. Additionally, the data adapter contains command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data. You will have a data adapter defined for each table in a DataSet and it will take care of all communication with the database for you. All you need to do is tell the data adapter when to load from or write to the database.
**Differences between DataSet and DataReader?Answer-Following are some major differences between DataSet and DataReader:
--------------------
CHAPTER-14 (Introduction to ASP.NET)
1. What is a web service ? Explain its working.
Answer-
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.
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 does the web service is different from web page?
Answer-
The differences between a Web service and a Web page are the following-
1.Web Services have No User Interface
but Web Page Has a User Interface.
2.Web Services Interacts with application and Web Page Interacts with the user.
3.Web Services Works with any type of client but Web Page Works with web browser client.
3. What is ASP.NET?
Answer-
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 .
4. What is use of ASP.NET?
Answer-
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.
5. Write a program to display “Welcome to ASP.NET” 8 times in increasing order of their font size using ASP.NET.
Answer-
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:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication9.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body MS_POSITIONING="GridLayout">
<form id="Form2" method="post" runat="server">
<%for(int i=0;i<8;i++){%>
<font size="<%=i%>">Welcome to ASP.NET ChandU</font><br/></font>
<%}%>
</form>
</body>
</html>
6. What is the role of System.Web?
Answer-
The System.Web namespace supplies classes and interfaces that enable browser and server communication. This namespace includes the HttpRequest class that provides extensive information about the current HTTP request, the HttpResponse class that manages HTTP output to the client, and the HttpServerUtility class that provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control.
7. Write a program to demonstrate handling of server control programs.
Answer-
ddlcountry.Items.Add("Bangladesh");
ddlcountry.Items.Add("Bhutan");
ddlcountry.Items.Add("India");
ddlcountry.Items.Add("Nepal");
ddlcountry.Items.Add("Pakistan");
ddlcountry.Items.Add("Sri Lanka");
CompareValidator1.ControlToValidate="txtcpassword";CompareValidator1.ControlToCompare="txtpassword";CompareValidator1.Text="The values of Password and Confirm Password fields does not match";
RequiredFieldValidator1.ControlToValidate="txtuname";RequiredFieldValidator1.Text="Please enter a user name";
RequiredFieldValidator2.ControlToValidate="txtpassword";RequiredFieldValidator2.Text="Please enter a password";
RequiredFieldValidator3.ControlToValidate="txtcpassword";RequiredFieldValidator3.Text="Please re-enter the password";
10. In the Click event of btnsubmit, enter the following code:
if(IsValid)
{
lblmessage.Text="Welcome "+ txtfname.Text +" "+txtlname.Text +
".You have successfully registered.";
}
11. Execute the application.
8. Explain briefly the web services provided by ASP.NET.
Answer-
9. Write a note on ASP.NET class library.
Answer-
The .NET Framework class library is a library of classes, interfaces, and value types that provide access to system functionality. It is the foundation on which .NET Framework applications, components, and controls are built.
--------------------
1. What is .NET?
Answer-
The .NET is
2. What is .Net Framework?
Answer-
The .NET Framework is a technology that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the following objectives:
3. What is .Net technology? Describe briefly its origins.
Answer-
Microsoft's .NET technology is a technology intended to connect. What to connect? Well the whole thing that can be linked through software - people, structures, computers, and extra things as well as devices.
A further thorough explanation of .NET would be to it is a top rank domain, at the start designed to be used by Internet Service Providers (ISP), but now it has extended and everybody can create use of a .net domain. It uses the Internet domain Naming System (DNS) and it is a contraction of the word 'Network'.
NET depends on four Internet standards:
Microsoft views this new technology as revolutionary, enabling Internet users to do things that were never before possible, such as integrate fax, e-mail and phone services, centralize data storage and synchronize all of a users computing devices to be automatically updated.
4. What is web service? How it is achieved using .Net strategy?
Answer-
A Web service is a method of communication between two electronic devices over r World Wide Web. A web service is a software function provided at a network address over the web or the cloud; it is a service that is "always on" as in the concept ofutility computing.
5. What is Microsoft Intermediate Language ?
Answer-
Microsoft Intermediate Language is a CPU-independent instruction set.
When you compile a .NET Framework application, it is converted into MSIL.
When you execute the .NET Framework application on a computer, the instructions specified in MSIL are translated into the native code.
MSIL ensure cross-language integration.
Note that MSIL is not interpreted.
6. With what objectives .NET framework is designed. Explain.
Answer-
The .NET Framework is designed to fulfill the following
objectives:
Some Other Objectives of Dot Net Framework:
7. What is Visual Studio.Net ?
Answer-
Visual Studio .NET is just an editor, provided by Microsoft to help developers write .NET programs easily. VS.NET editor
automatically generates lot of code, allows developers to drag and drop controls to a form, provide short
cuts to compile and build the application etc.
8. List the different languages supported by .NET?
Answer-
List of the different languages supported by .NET
C#, VB .Net, j#,C++ .
Cobol,Component Pascal ,Curriculum ,Eiffel ,Forth ,Fortran, Haskell ,Java Language ,Microsoft JScript,Mercury ,Mondrian, Oberon ,Oz ,Pascal, Perl ,Python, RPG ,Scheme, Small Talk, Standard ML,
9. With a neat diagram explain relationship of the common language runtime and the class library to your
application.
Answer-
10. Explain salient features of common language runtime.
Answer-
The Common Language Language Runtime is robust and secure because it includes the following features:
11. Briefly explain what types of applications and services can be developed using .NET framework.
Answer-
--------------------
CHAPTER-2 (Overview of the .NET Framework)
1. What are the components of .NET framework?
Answer-
.Net Framework is a platform that provides tools and technologies to develop Windows, Web and Enterprise applications. It mainly contains two components,
1. Common Language Runtime (CLR)
2. .Net Framework Class Library.
2. What is Common Language Run-time?
Answer-
The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier.
3. Enumerate major services provided by CLR.
Answer-
CLR is a common runtime environment for .NET languages.
The core services of CLR are
4. How does CLR implements C# program?
Answer-
5. What is Common Type System?
Answer-
The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self describing.
6. What is common Language Specification?
Answer-
Common Language Specification is a standard for .net. Common Language Specification is small set of specification to make all languages as a .net compliant languages. cls make a use of cts and clr. if my languages (c#,vb.net,j#,vc++) wants to be compliant language it has to follow cls standard.
7. What is manages code?
Answer-
Managed code is not compiled to machine code but to an intermediate language which is interpreted and executed by some service on a machine and is therefore operating within a (hopefully!) secure framework which handles dangerous things like memory and threads for you. In modern usage this frequently means .NET but does not have to.
8. List some of the important services the Framework Base Classes offer to the user.
Answer-
9. What are the benefits of .Net strategy advanced by Microsoft?
Answer-
The main benefits of t.NET are:
* Makes programming easier thanks to Web services
* Allows the use of different programming languages
* Offers an integrated set of tools for building and integrating Web services
10. Explain the following.
a. MetaData
--metadata is data about data. It is descriptive information about a particular data set, object, or resource, including how it is formatted, and when and by whom it was collected.
b. Cross Language Interoperability
--Language Interoperability means developing one application with more than one language.
Suppose u are developing vb.net application and u need to work with COM components of vb6.0,then it is called language interoperability.
c. Assembliesd.
--Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations.
d.Application Domains
--Application domains provide an isolation boundary for security, reliability, and versioning, and for unloading assemblies. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run.
e. .NET framework class library
The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, thirdparty components can integrate seamlessly with classes in the .NET Framework
f. System Namespace
--The System namespace is the root namespace for fundamental types in the .NET Framework. This namespace includes classes that represent the base data types used by all applications: Object (the root of the inheritance hierarchy), Byte, Char, Array, Int32, String, and so on. Many of these types correspond to the primitive data types that your programming language uses. When you write code using .NET Framework types, you can use your language’s corresponding keyword when a .NET Framework base data type is expect.
11. Briefly explain the different base data type supported by .NET framework
Answer-
Script data type--C++ datatype--.NET Framework class (C# data )
Number int Int32 (int)
Number long Int32 (int)
Number double Double (double)
Number float Single (float)
String BSTR String (string)
Boolean VARIANT_BOOL Boolean (bool)
Object Object Object (object)
--------------------
CHAPTER-3 (Architecture of .NET Framework)
1. With a neat diagram explain the architecture of .NET framework.
Answer-
2. List out the objectives of .Net Framework.
Answer-
The Main Objectives of .NET Framework are-
1) Platform Independent
2) Language Independent
3) Language Interoperability
4) Security
5) Database Connectivity
6) Globalization of Application
Some Other Objectives of Dot Net Framework are:
3. How the windows programming is different from .Net programming?
Answer-
The windows programming is different from .Net programming
-Windows Programming - In Windows Programming the application programs call windows API function directly. The applications run in the windows environment i.e. operating system itself. These types of applications are called unmanaged or unsafe applications.
.NET Programming - In .NET Programming the application programs call .Net Base Class library functions which will communicate with operating system. The applications run in .Net Runtime environment. These types of applications are called as managed or safe applications. The .Net Runtime starts code execution, manages threads, provides services, manages memory etc. The .Net Base classes are fully object-oriented. It provides all functionalities of traditional windows API along with functionalities in new areas like accessing database, internet connections and web services.
4. What are the functionalists of CLR ? Give the steps involved in managed code execution process.Answer-
The CLR has the following functionalists:
The managed execution process includes the following steps:
5. What are assemblies? What are static and dynamic assemblies?Answer-
Assemblies are the basic elements 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.
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 PE files.
Dynamic Assemblies are one which run directly from memory and are not saved to disk before execution. They can be saved to disk after they have executed.
6. How the .Net execution environment with application domain differs from traditional way of execution?
Answer-
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.
7. What is CTS? Explain the classification of types in CTS with a diagram.Answer-
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.
Classification of Types The CTS supports two categories:
* Value Types – It directly stores data in the variable. Value types can be built-in type, user defined types or enumerations.
* Reference Types – It 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.
8. Write a note on metadata.Answer-
Metadata is the key to a simpler programming model, and eliminates the need for Interface Definition Language (IDL) files, header files, or any external method of component reference. Metadata enables .NET Framework languages to describe themselves automatically in a language-neutral manner, unseen by both the developer and the user. Additionally, metadata is extensible through the use of attributes.
Metadata provides the following major benefits:
*Self-describing files.
Common language runtime modules and assemblies are self-describing. A module’s metadata contains everything needed to interact with another module. Metadata automatically provides the functionality of IDL in COM, so you can use one file for both definition and implementation. Runtime modules and assemblies do not even require registration with the operating system. As a result, the descriptions used by the runtime always reflect the actual code in your compiled file, which increases application reliability.
* Language interoperability and easier component-based design.Metadata provides all the information required about compiled code for you to inherit a class from a PE file written in a different language. You can create an instance of any class written in any managed language (any language that targets the common language runtime) without worrying about explicit marshaling or using custom interoperability code.
* Attributes.
The .NET Framework lets you declare specific kinds of metadata, called attributes, in your compiled file. Attributes can be found throughout the .NET Framework and are used to control in more detail how your program behaves at run time. Additionally, you can emit your own custom metadata into .NET Framework files through user-defined custom attributes
9. With a neat diagram explain the architecture of Common Language Runtime.
Answer-
10. Briefly explain the following.
a. Managed Code
-> Managed code is code that has its execution managed by the .NET Framework Common Language Runtime. It refers to a contract of cooperation between natively executing code and the runtime. This contract specifies that at any point of execution, the runtime may stop an executing CPU and retrieve information specific to the current CPU instruction address. Information that must be query-able generally pertains to runtime state, such as register or stack memory contents.
b. Unmanaged Code
-> The code, which is developed outside .NET, Framework is known as unmanaged code.
Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - levefunctions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code.
c. Microsoft Intermediate Language-> It is language independent code. When you compile code that uses the .NET Framework library, you don’t immediately create operating system - specific native code.
Instead, you compile your code into Microsoft Intermediate Language (MSIL) code. The MSIL code is not specific to any operating system or to any language.
d. Just-In-Time Compiler-> Just - in - Time (JIT) compiler, which compiles MSIL into native code that is specific to the OS and machine architecture being targeted. Only at this point can the OS execute the application. The just - in -time part of the name reflects the fact that MSIL code is only compiled as, and when, it is needed.
e. Garbage Collector-> One of the most important features of managed code is the concept of garbage collection. This is the .NET method of making sure that the memory used by an application is freed up completely when the application is no longer in use.
(As CLR is smart to free up the memory, so why Microsoft has given option for pro grammatically calling Garbage collect)
11. Explain the different process of executing the C# code which is written using .NET framework
Answer-
The different process of executing the C# code which is written using .NET framework -
Step 1-Application code is written using a .NET - compatible language C#.
Step 2 -Code is compiled into MSIL, which is stored in an assembly.
Step 3 -When this code is executed (either in its own right if it is an executable or when it is used from other code), it must first be compiled into native code using a JIT compiler.
Step 4 -The native code is executed in the context of the managed CLR, along with any other running applications or processes.
Note: One additional point concerning this process. The C# code that compiles into MSIL in step 2 needn’t be contained in a single file. It’s possible to split application code across multiple source code files, which are then compiled together into a single assembly. This extremely useful process is known as linking.
This is because it is far easier to work with several smaller files than one enormous one. You can separate out logically related code into an individual file so that it can be worked on independently and then practically forgotten about when completed.
--------------------
CHAPTER-4 (Getting started with C# in the .NET framework)
1. With a neat diagram explain the components of .NET framework.
Answer-
2. Explain the important features of .NET.Answer-
The important features of .NET are-
OTHER FEATURES--
*Common Type System -
Language interoperability under .NET is possible only when all the languages share a common data type system. For this, the common type system (CTS) is introduced. CTS ensures that an int in C# is same as an int in VC++. Under CTS, all the classes are derived from the System.Object class and all the primitive data types are mapped to the structures defined in base class library. CTS also specifies the visibility level (from where the type should be accessible) of data types.
*Intermediate Language -
A .NET programming language does not compile into executable code; instead it compiles into an intermediate code called Microsoft Intermediate Language (MSIL). IL is a CPU-independent language. The IL code is sent to the CLR that converts the code to machine language using the Just In Time compiler, which is then run on the host machine. An important aspect of the IL Windows Forms, Web Forms, Web Services, etc.
(Developed in .NET compliant languages) .NET Framework Base Classes (ADO.NET, XML, Threading, I/O, Network) Common Language Runtime (Memory ) Management, Common Type System, Lifecycle Monitoring) 33 language is that it provides the hardware abstraction layer. We can view the IL code of our application using the ILDASM tool shipped with Visual Studio.NET.
*JIT Compilation-
JIT (Just In Time) compiler is a crucial component of the .NET framework. The JIT compiler converts IL code into machine code, which is then executed. The JIT compiler does not compile the entire code at once because it could hamper the performance of the program. It compiles the code at runtime, at the time it is called. The code that is compiled gets stored until the execution comes to an end. This avoids recompilation of code. The reason why conversion from IL code to machine code takes place at runtime is that the JIT first gets information on the processor type and appropriately converts the IL code so that it would run on that type of processor.
* Assemblies-
An assembly is a unit containing IL code of a program. It is similar to a DLL file, but one
difference is that unlike DLL, an assembly is self-describing. Assemblies contain assembly metadata (or manifest) that gives details of the assembly, type metadata describing the types, methods, etc, defined in the assembly and resources.
Garbage Collection Garbage Collection is a program that is invoked by the CLR to free the memory that is not being used by the application. Because of this technique the programmers no more need to take care of memory leakages, dangling pointers and clean up of memory.
That’s it for a brief introduction to the .NET framework. Let us now create a simple program in C# hat uses the .NET framework. It is assumed that you have installed Visual Studio.NET on a machine running under Windows NT/2000/XP
3. Write down the steps to be followed while creating a C# program.Answer-
The steps to create the program are given below.
(a) Start Microsoft Visual Studio.NET from ‘Start | Program | Microsoft Visual Studio.NET’menu option.
(b) Create a new C# project by selecting ‘File | New | Project menu option. A ‘New Project’
dialog would appear. From the ‘New Project dialog box select project type as ‘Visual C#
Projects’.
(c) Select ‘Console Application ’from the list of Templates.
(d) Select a location where this project should get saved. Name the project as Simple. Click the OK button.
(e) A ‘Class1.cs file (cs stands for C Sharp) would get created with the skeleton code given
below:
using System;
namespace Simple
{
class Class1
{
void Main ( string[ ] args )
{
Console.WriteLine ( “Hello C#” );
}
}
}
4. Describe the structure of typical C# program.Answer-
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 skeleton of a C# program that contains all of these elements.
// A skeleton of a C# program
using System; namespace Namespace1
{
class Class1
{
}
struct Struct1
{
}
interface Interface1
{
}
delegate int Delegate1();
enum Enum1
{
}
namespace Namespace2
{
}
class Class2
{
public static void Main(string[] args)
{
}
}
}
5. Why do we use the using directive in a C# program?Answer-
The using directive has two uses:
1. To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:
using System.Text;
2.To create an alias for a namespace or a type. This is called a using alias directive.
using Project = PC.MyCompany.Project;
6. What is the importance of the Main method in a C# program?Answer-
The Main method is the entry point of a C# console application or windows application. When the application is started, the Main method is the first method that is invoked. (The program execution starts from the Main()function. Since C# is a pure object-oriented language it does not allow us to create global variables and fun
7. Why do we use comments in a program?Answer-
Code comments are the "first line" of program documentation. They are used to tell other programmers how your code works, what it's doing, and what they need to know in order to understand it as well as you do.
8. Describe the difference between the two styles of comments used in C#.Answer-
In C# language, the types are divided into two styles of comments:
9. How does the Write() method is different from WriteLine() method?Answer-
The Write () method outputs one or more values to the screen without a new line character.
The WriteLine() always appends a new line character to the end of the string. this means any subsequent output will start on a new line.
tions. Instead, all variables and functions including Main() should be defined inside a class)
10. What is syntax error? How do we detect them?Answer-
These are errors where the compiler finds something wrong with your program, and you can't even try to execute it. For example, you may have incorrect punctuation, or may be trying to use a variable that hasn't been declared.
Syntax errors are the easiest to find and correct. The compiler will tell you where it got into trouble, and its best guess as to what you did wrong. Usually the error is on the exact line indicated by the compiler, or the line just before it; however, if the problem is incorrectly nested braces, the actual error may be at the beginning of the nested block.
11. Write a C# program to display the text “Hello C#”. Explain it.
Answer-
using System;
namespace Simple
{
class Class1
{
static void Main ( string[ ] args )
{
Console.WriteLine ( “Hello C#” );
}
}
--------------------
CHAPTER-5 (C# Language Syntax)
1. With an example explain how to declare variables in C#.Answer-
The following sample shows different ways you can declare a variable:
int a;
int salary, incomeTax, sum;
int count = 10;
string name;
string fullName= “ChandU”;
2. With an example explain the following loop statements in C#.
a. While
Answer-
int i = 0;
while ( i < 5 )
{
Console.WriteLine ( i );
++i;
}
(The above loop repeates 5 times and prints the value of i.
The output of above code would be like this :
0
1
2
3
4)
b. Do..While-
Answer-
int i = 0;
do
{
Console.WriteLine ( i );
i++;
}
while ( i < 5 );
(The above loop is pretty much same as the whileloop. The only difference is, the condition is checked
only after executing the code inside the loop)
c. For-Answer-
for ( int i = 0; i < 5; i++ )
{
Console.Wr iteLine ( i );
}
(The above loop repeats 5 times just like the whileloop and prints the value of i.
The output of above code would be like this :
0
1
2
3
4)
d. Foreach-Answer-
string [ ] names = new string[ ]{ “Abhilash",“Balram”,“ChandU” ,"Sekhar” };
foreach ( string name in names )
{
Console.WriteLine ( name );
}
(foreach loop can be used to iterate through a collection like array,
ArrayList etc.
The above code displays the following output.
Abhilash
Balram
ChandU
Sekhar)
3. With an example explain break and continue statement in C#.Answer-
Break --
‘break’s tatement is used to break out of loops
(‘while’, ‘for’, switch’etc).
string [] names = new string[]{ “Abhilash",“Balram”,“ChandU” ,"Sekhar” };
foreach ( string name in names )
{
Console.WriteLine ( name );
if ( name == “ChandU” )
break;
}
In the above sample, it iterates through the array of 4 items, but when it encounters the name “ChandU”,
it exits the loop and will not continue in the loop anymore.
The output of above sample would be :
Abhilash
Balram
ChandU
Continue-- ‘continue statement is also used to in the loops (‘while’, for, etc). When executed, continue statement will move the execution to the next iteration in the loop, without continuing the lines of code after the ‘continue' ’inside the loop.
string [ ] names = new string[ ]{ “Abhilash",“Balram”,“ChandU” ,"Sekhar” };
foreach ( string name in names )
{
if ( name == “ChandU” )
continue;
Console.WriteLine ( name );
}
In the above sample, when the value of name is “ChandU”, it executes the ‘continue’ which will change the execution to the next iteration, without executing the lines below it. So, it will not print the name, if the name is “ChandU”.
The output of above sample would be :
Abhilash
Balram
Sekhar
4. Write a program to print whether a given number is even or odd.Answer-
Program that finds odd numbers :-
using System;
class Program
{
static void Main()
{
for (int i = 0; i <= 100; i++)
{
if (IsOdd(i))
{
Console.WriteLine(i);
}
}
}
public static bool IsOdd(int value)
{
return value % 2 != 0;
}
}
Output- 1, 3, 5, 7, 9, 11, 13,.................................99
----------
Program that finds even numbers:-
using System;
class Program
{
static void Main()
{
for (int i = 0; i <= 100; i++)
{
if (IsEven(i))
{
Console.WriteLine(i);
}
}
}
public static bool IsEven(int value)
{
return value % 2 == 0;
}
}
Output- 0., 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,......................100.
5. Write a program to print all possible roots of the quadratic equation ax2+bx+c=0.Answer-
6. Write a program to print the factorial of a given number.Answer-
You may write a class called 'Calculator' with a method called 'Factorial()' taking one input parameter and returning the Factorial of the input.
public class Calculator
{
public int Factorial(int a)
{
int factorial = 1;
while ( a > 0 )
{
factorial *= a;
--a;
}
return factorial;
}
}
7. Write a program to print the first n terms of the Fibonacci series.Answer-
using System;
class Program
{
public static int Fibonacci(int n)
{
int a = 0; int b = 1;
for (int i = 0; i < n; i++)
{
int temp = a; a = b; b = temp + b;
}
return a;
}
static void Main()
{
for (int i = 0; i < 15; i++)
{
Console.WriteLine(Fibonacci(i));
}
}
}
Output- 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,.........................n.
8. Write a program to reverse the given number.Answer-
using System;
static class StringHelper
{
public static string ReverseString(string s)
{
char[ ] arr = s.ToCharArray();
Array.Reverse(arr); return new string(arr);
}
}
class Program
{
static void Main()
{
Console.WriteLine(StringHelper.ReverseString("54321"));
Console.WriteLine(StringHelper.ReverseString("98765"));
}
}
Output- 12345, 56789
9. Write a program to find the sum of the digit of a given number.Answer-
using System;
using System.Collections.Generic;
using System.Text;
namespace SumOfDig
{
class Program
{
static void Main(string[] args)
{
long modulo,sum=0;
Console.Write("Enter the Number:");
long number = long.Parse(Console.ReadLine());
while (number > 0)
{
modulo = (number % 10);
sum = sum + modulo;
number = number / 10;
}
Console.WriteLine("The Sum of Digits of number is {0}",sum);
Console.ReadLine();
}
}
}
10. Demonstrate the typical use of goto statement.Answer-
using System;
class Program
{
static void Main()
{
int main()
{
float num,average,sum;
int i,n; printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump;
sum=sum+num;
}
jump: average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
11. Compare and contrast if..else statement and switch statement.
Answer-
They are pretty similar but each has a few special features.
if-else
switch
--------------------
CHAPTER-6 (DataTypes in C#)
1. Briefly explain data types in C# and .NET.Answer-
DataTypes are the basic building block of any language. Microsoft has tried to standardise the datatypes in .NET framework by introducing a limited, fixed set of types that can be used to represent almost anything in programming world.
C++ was very rich in datatypes, but that leads to confusion too. Especially, when you write components that may be consumed by applications written in other platforms, you have to make sure the types used are compatible with other platforms too!
.NET types start from a clean slate. All .NET languages share the same types. So, they are all compatible and no worries.This means, you can call C# code from VB.NET and vice versa, without worrying about type conversions.
.NET data types are either structures or classes, part of the System namespace. For example, the following data types are implemented as struct in .NET:
*Int16
*Int32
*Double
(String is implemented as a class in .NET, for various reasons.)
If you are not very familiar with struct and class, don’t worry about it. You can just use them as if they are simple data types.
Here is how you can declare variables of type Int, Double and String:
*Int16 age, employeeNumber;
* Double salary;
*String name, address;
You can use any of the .NET data types directly in any .NET language - in C#, VB.NET or
xyz.NET.But in addition to the .NET types, each language provides a set of primitive types, which map to the corresponding types in .NET class library. This is why you may see some people use string and some others use String. There is no big difference. string is a primitive data type in C# and String is the corresponding class in .NET class library. The string in C# is mapped to the class in .NET class library. So, whether you use string or String,there is no real difference.
2. List the data types in C# and their corresponding class/struct in .NET class library.Answer-
The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library.
C# Data type Mapped to .NET class/struct
Sbyte Sys tem.SByte
Byte System.Byte
Char System.Char
Float System.Single
Decimal System.Decimal
Double System.Double
Ushort System.UInt16
Short System.Int16
Uint System.UInt32
Int System.Int32
Ulong System.UInt64
Long System.Int64
Bool System.Boolean
String System.String
Object System.Object
3. What is a literal?Answer-
A literal is some data that's presented directly in the code, rather than indirectly through a variable or function call.
(A literal is a value that is expressed as itself. For example, the number 25 or the string "Hello World" are both literals. )
4. What is a constant?Answer-
A constant is a value that never changes. The other type of values that programs use is variables, symbols that can represent different values throughout the course of a program.
A constant can be
a number, like 25 or 3.6
5. What is variable?Answer-
In programming, a variable is a value that can change, depending on conditions or on information passed to the program. Typically, a program consists of instruction s that tell the computer what to do and data that the program uses when it is running.
6. There are thirteen simple value types. List Them.
Answer-
Thirteen simple value types
1.SByte
2.byte
3.char
4.ULong
5.long
6.UInteger
7.int
8.double
9.short
10.UShort
11.float
12.bool
13.decimal
7. List the two different reference types.Answer-
Variables of reference types store references to the actual data. This section introduces the following keywords used to declare reference types:
1.class
2.interface
8. Differentiate between value types and reference data types in C#
Answer-
The differences between values types and reference types :-
1)value types allocated on stack but reference types allocated on heap.
2). A value type variable contains the data itself but reference type variable contains the
address of memory location where data is actually stored.
3). When you copy a value type variable to another one, the actual data is copied and each variable can be independently manipulated but when copying a reference type variable to another variable, only the memory address is copied. Both variables will still point to thesame memory location, which means, if you change one variable, the value will be changed for the other variable too.
4). Integer, float, boolean, double etc are value types and string and object are reference types.
5). Struct is value type but classes and interfaces are reference type
--------------------
CHAPTER-7 (Classes and Object model in .NET)
1. With an example explain class and methods.Answer-
In modern object oriented programming, large computer programs are divided into several ‘classes’. Typically, a large project will have several hundred classes. A class represents an entity in a program.
For example, if you are doing a small program called calculator, you will typically have a single (or more) class called ‘Calculator’(you can give any name for your class). The class will have several ‘methods’, that will do the functionality of the class.
So, your calculator may have methods like the following:
Add()
Subtract()
Multiply()
Divide()
A sample calculator class, written in C# is given below:
using System;
public class Calculator
{
public int Add(int value1, int value2)
{
return value1 + value2;
}
public int Subtract(int value1, int value2)
{
return value1 - value2;
}
public int Multiply(int value1, int value2)
{
return value1 * value2;
}
public int Divide(int value1, int value2)
{
return value1 / value2;
}
}
2. With an example explain get and set properties in a class.Answer-
public class Car
{
private string color;
public Car()
{
}
public string Color
{
get
{
if ( color == “” )
return “GREEN”;
else
return color;
}
set
{
if ( value == “” )
thrown new Exception (“Wrong value.”);
else
color = value;
}
}
}
3. How do we invoke a method in C#?Answer-
using System;
using System.Reflection;
class Program
{
public void Win()
{
Console.WriteLine("{You're a winner}");
}
public void Lose()
{
}
public void Draw()
{
} static void Main()
{
Program p = new Program();
MethodInfo [ ] methods = type of(Program).GetMethods();
foreach (MethodInfo info in methods)
{
Console.WriteLine(info.Name);
if (info.Name == "Win")
{
info.Invoke(program, null);
}
}
}
}
4. What is nesting of methods? Give an example of typical use of methods nesting?Answer-
A type defined within a class or struct is called a nested type. For example:
5. Describe three different ways of providing values to instance variables of a class?Answer-
6. Describe two ways of accessing the values of data fields? Compare them.Answer-
7. What is property? Why are they referred as smart fields?Answer-
8. List at least three important features of properties.Answer-
9. Create a class to hold two integer values. Design a method swap that would take two integer object as parameters and swap their contents.
Answer-
10. What do you mean by name spaces. List the name spaces available in .NET class library.
--------------------
CHAPTER-8 (WinForms)
1. Write a note on the following.
a. Winform-
WinForms is the most commonly used feature of .NET.
'Windows' based applications in .NET is called 'WinForms'. The .NET framework comes with a good number of classes to support 'Form' based application development.
A WinForm application will have atleast one ‘Form’(window), which would be used for the interaction
between the application and user. A Form can contain other controls like TextBox, Label, Button etc.
Large WinForms applications will have several ‘Forms’, some of them used to capture data from user and
some of them used to display data to user. By performing certain actions in each form, user can navigate
to other ‘Forms’in the application.
b. Event Driven Programming-
Event Driven programming model is the most commonly used feature in modern programming. In this
model, you will write appropriate code for each event. Examples for events are
Button Click
Mouse Move
Mouse Click
Key Press
In Winforms application, users interact with the application using various actions in the window (likeclicking a button, moving mouse, pressing keys in keyboard etc). These actions will generate various
events. When an event is generated, the code written for that event will be executed.
2. Write the steps to create Winform applications.Answer-
TO CREATE WINFORMS APPLICATIONS:
3. Briefly discuss the various controls available in System.Windows.Froms.Answer-
4. Write a C# program to create and display a window.Answer-
5. Briefly explain the MessageBox class.Answer-
6. Briefly explain the different types of event that can be generated.Answer-
7. With the help of an example program explain how to add button control to the window.Answer-
8. Write a program to display a message box and read the data entered in the text box. Briefly explain.
Answer-
--------------------
CHAPTER-9 (Inheritance)
1. With an example program explain the inheritance concept in C#.Answer-
As with most programming concepts the subject of inheritance in C# is perhaps best illustrated with an
example. In the previous chapter we created a class called BankAccount:
public class BankAccount
{
public string accountName;
public int accountFee;
private int accountBalance;
private int accountNumber;
public int getAccountNumber()
{
return accountNumber;
}
public void setAccountNumber(int newNumber)
{
accountNumber = newNumber;
}
}
This class does a good job of defining characteristics common to any type of bank account, such as
account holder name, account number and current balance. Imagine, however, that our banking program
needs to support a number of specific types of account. For example, the bank might offer its customers
an interest bearing savings account. A savings account will have all the characteristics of our BankAccount
class but would also need a way to store the prevailing interest rate. One option would be to create a
brand new class from the ground up called SavingsAccountwhich duplicates everything we have in our
BankAccountclass, plus extra members needed for a savings account. Another, more efficient method is
to derive a SavingsAccountclass from the BankAccountclass and then add in the extra functionality
into this subclass.
2. What is re-usability of code? How it is achieved in C#?Answer-
3. What are two forms of inheritance? Give your own examples.Answer-
4. Describe the syntax of single inheritance in C#.Answer-
5. Describe improvement characteristics of inheritance.Answer-
6. How does a base class receive its arguments in order to construct its members properly?Answer-
7. When do we declare a class abstract?Answer-
When at least one of the methods in the class is abstract.
The keyword abstract can be used with both classes and methods in C# to declare them as abstract.
The classes, which we can't initialize, are known as abstract classes. They provide only partial implementations. But another class can inherit from an abstract class and can create their instances.
8. State the characteristics of abstract classes.Answer-
The characteristics of abstract classes-
9. What are the characteristics of abstract methods?Answer-
Characteristics of abstract method are:-
10. What is virtual method?
Answer-
A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overriden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overriden in the derived class using the override keyword
11. With an example program explain how to pass arguments to the base class constructors.Answer-
using System;
class Net
{
public string Name { get; set; }
public Net(Perl perl)
{
// Use name from Perl instance.
this.Name = perl.Name;
}
}
class Perl
{
public string Name { get; set; }
public Perl(string name)
{
this.Name = name;
// Pass this instance as a parameter!
Net net = new Net(this);
// The Net instance now has the same name . Console.WriteLine(net.Name);
}
}
class Program
{
static void Main()
{
Perl perl = new Perl("Sam");
}
}
12. Write a note on abstract class.Answer-
Often a base class is not intended to be instantiated and is provided solely for the purpose of providing an outline for subclasses. Such a class is known as an abstract class.
13. Differentiate between abstract and virtual members.
Answer-
- Only abstract classes can have abstract members.
- A non-abstract class that inherits from an abstract class mustoverride its abstract members.
- An abstract method is implicitly virtual.
- An abstract method cannot provide any implementation.
- A class can have a virtual method.
- The virtual method has an implementation. When you inherit from a class that has a virtual method, you can override the virtual method.
--------------------
CHAPTER-10 (Exception Handling)
1. What are compile time errors? Give some examples. How are they detected?Answer-
2. What are run time errors? Give some examples. How are they detected?
3. What is exception? Give some examples.
Answer-
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
Some examples of exception:-
4. Why is it necessary to handle an exception by a special code?
Answer-
5. Describe the tasks involved in handling exceptions.
Answer-
6. How do you define the following.
a) try block--
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.
b) catch block--
In catch we handle exceptions. The try-catch pattern in the C# language provides an alternative flow control. It traps errors in an efficient and clear way. The catch block allows an optional variable.
Multiple catch blocks can be stacked to provide more control. The final one does not require a variable type.
c) finally block--
If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
7. What do you mean by Exceptions? With the help of an example program explain how exception is handled in C#.
Answer-
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.
8. List at least four exceptions that occur in C# programs.
Answer-
9. What happens when a try block is neither followed by a try block nor ny a finally block.
Answer-
10. What is the purpose of using finally block? Give some examples.Answer-
11. When do you consider it necessary to define your own exception classes?Answer-
12. With an example program explain how to throw your own exceptions.Answer-
13. Briefly explain Standard Exceptions.Answer-
14. Write a note on user defined Exceptions.
Answer-
--------------------
CHAPTER-11 (Arrays)
1. What do you mean by arrays? Explain how define and initialize arrays in C#.
Answer-
2. Differentiate between Rectangular arrays and Jagged arrays.
C# supports two types of multidimensional arrays:
Rectangular and Jagged.
A rectangular array is a single array with more than one dimension, with the dimensions’sizes fixed in the array’s declaration. The following code creates a 2 by 3 multi-dimensional array.
A jagged arrays, one can create multidimensional arrays with irregular dimensions. This flexibility
derives from the fact that multidimensional arrays are implemented as arrays of arrays. The following
piece of code demonstrates how one might declare an array made up of a group of 4 and a group of 6
elements:
3. Explain the need for array variables.
Answer-
4. What is a variable size array? How is it different from a rectangular array?Answer-
5. Give an example of typical use of variable size array.Answer-
6. Write a program to add two matrices.Answer-
using System;
using System.Collections.Generic;
using System.Text;
namespace Add_Two_Matrix
{
class Program
{
static void Main(string[] args)
{
int[,] a = {{1, 2, 3 }, { 4, 5, 6 }, { 7,8,9} };
int[,] b ={ { 4, 8, 7 }, { 6,5,4}, {3,2,1 } };
int[,] c = new int[3,3];
int f = c.Length;
int i, m = 0;
int j = 0;
int n = 0;
for ( i = 0;i<3;i++)
{
Console.WriteLine(" ");
for (j = 0; j < 3; j++)
{
Console.Write(" " + a[i, j]);
}
}
Console.Write("\n");
for ( m = 0; m < 3; m++)
{
Console.WriteLine(" ");
for ( n = 0; n < 3; n++)
{
Console.Write(" " + b[m, n]);
}
}
Console.Write("\n");
for (int k = 0; k < 3; k++)
{
Console.WriteLine("");
for (int l = 0; l < 3; l++)
{
Console.Write(a[k, l] + b[k, l] + "\t");
}
}
Console.WriteLine();
Console.ReadLine();
}
}
}
7. Write a program to multiply two matrices.Answer-
The following C# program will take two matrices of 2*2 order in its input and then print the product of them.
using System;
using System.Collections.Generic;
using System.Text;
namespace matrix_muliplication
{
class Program
{
static void Main(string[] args)
{
int i,j,k,l;
int[,] matrix=new int[2,2];
int[,] matri=new int [2,2];
int[,] matr=new int [2,2];
Console.WriteLine("Enter 1st 2*2 matrix: \n");
for (i=0;i<2;++i)
{
Console.WriteLine("Enter "+ (i+1) +"# row: ");
for (j=0;j<2;++j)
{
matrix[i,j]=Int32.Parse( Console.ReadLine());
}
}
Console.WriteLine("\n");
Console.WriteLine("Enter 2nd 2*2 matrix: \n");
for (i=0;i<2;++i)
{
Console.WriteLine("Enter "+(i+1)+" # row: ");
for (j=0;j<2;++j)
matri[i,j]=Int32.Parse(Console.ReadLine());
}
Console.WriteLine();
Console.WriteLine("Matrix muliplication");
for (j=0;j<2;++j)
{
for (i=0;i<2;++i)
{
for (l = 0; l < 2; ++l)
{
matr[i, j] = matr[i, j] + (matrix[i, l]) * (matri[l, j]);
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(matr[i, j] + "\t");
}
Console.WriteLine();
}
}
}
}
8. Write a program to find row sum and column sum of a matrix.Answer-
using System;
using System.Collections.Generic;
using System.Text;
class mat
{
int i, j, m, n;
int[,] a = new int[20, 20];
public void get()
{
Console.WriteLine("Enter Row Value");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Column Value");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Elements one by one");
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
a[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("Given Matrix");
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
Console.Write("\t{0}", a[i, j]);
}
Console.WriteLine();
}
}
public void diag()
{
int d;
d = 0;
if (m == n)
{
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
if (i == j)
{
d = d + a[i, j];
}
}
}
Console.WriteLine("Diagonal Sum= {0}", d);
}
else
{
Console.WriteLine("Can't Perform Diagonal Sum");
}
}
class matsum
{
static void Main(string[] args)
{
mat ma = new mat();
ma.get();
ma.diag();
Console.Read();
}
}
}
OUTPUT-
Enter Row Value : 2
Enter Column Value : 2
Enter Elements One by One : 2, 2
2 ,2
Given Matrix : 2, 2
2 , 2
Diagonal Sum :4
9. Write a program to verify whether a given matrix is identity matrix or not.
Answer-
include<stdio.h>
#include<conio.h>
void main()
{
int mat[5][5];
int n=3,i,j;
clrscr();
printf("\n\n Enter the order: ");
scanf("%d",&n);
printf("\n Enter the matrix\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf(" %d,%d: ",i+1,j+1);
scanf("%d",&mat[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if((i==j && mat[i][j]==1)||(i!=j && mat[i][j]==0))
continue;
else
{
printf("It is not identity matrix \n");
i=j=n;
}
}
}
if(i==j && i==n)
printf("It is identity matrix \n");
getch();
}
--------------------
CHAPTER-12 (C# Collection Classes)
1. What are C# collection classes? Explain briefly.
Answer-
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:
2. How does an array of ArrayList class different from Array class?Answer-
3. When do we decide to use the ArrayList class over the Array class?
Answer-
4. With an example explain how to create List and ArrayList classes in C#.
Answer-
5. With an example explain the following.
a. Adding items to list.
--Once a List object has been created there are a number of methods which may be called to perform tasks on the list. Once such method is the Add()method which, as the name suggests, is used to add items to the list object:
List<string> colorList = new List<string>();
colorList.Add (“Red”);
colorList.Add (“Green”);
colorList.Add (“Yellow”);
colorList.Add (“Purple”);
colorList.Add (“Orange”);
b. Accessing list items.
Individual items in a list may be accessed using the index value of the item (keeping in mind that the first item is index 0, the second index 1 and so on). The index value is placed in square brackets after the list name. For example, to access the second item in the colorListobject:
Console.WriteLine (colorList[1]);
A list item value can similarly be changed using the index combined with the assignment operator. For example, to change the color from Yellow to Ingido:
colorList[2] = “Indigo”;
All the items in a list may be accessed using a foreachloop.
For example-
foreach (string color in colorList)
{
Console.WriteLine ( color );
}
When compiled and executed, the above code will output each of the color strings in the colorList object.
--
c. Removing items from list.
Items may be removed from a list using the Remove()method. This method takes the value of the item to be removed as an argument. For example, to remove the “Red”string from the colorList object:
colorList.Remove(“Red”);
d. Inserting items into a list
--The Insert()method is provided for this specific purpose. Insert()takes two arguments, an integer indicating the index location of the insertion and the item to be inserted at that location. For example, to insert an item at location 2 in our example list:
colorList.Insert(2, “White”);
e. Sorting lists.
--There is no way to tell C# to automatically sort a list as items are added. If the items in a list are required to be always sorted into order the Sort()method should be called after new items are added-
colorList.Sort();
f. Finding items in a list
--A number of methods are provided with the List and ArrayList classes for the purposes of finding items. The most basic method is the Contains()method, which when called on a List or ArrayList object returns trueif the specified item is found in the list, or falseif it is not.
The IndexOf()method returns the index value of a matching item in a list. For example, the following code sample will output the value 2, which is the index position of the “Yellow”string:
List<string> colorList = new List<string>();
colorList.Add (“Red”);
colorList.Add (“Green”);
colorList.Add (“Yellow”);
colorList.Add (“Purple”);
colorList.Add (“Orange”);
Console.WriteLine(colorList.IndexOf(“Yellow”));
If the item is not found in the List a value of -1 is returned by the IndexOf()method.
This technique could be used to replace a specific value with another. For example, without knowing
in advance the index value of the “Yellow”string we can change to “Black”:
colorList[colorList.IndexOf(“Yellow”)] = “Black”;
The LastIndexOf()method returns the index value of the last item in the list to match the specified item. This is particularly useful when a list contains duplicate items.
g. Clearing the list.
--All the items in a list may be removed using the Clear()method:
colorList.Clear();
The Clear()method removes the items from the list and sets the Countproperty to zero. The Capacity property, however, remains unchanged. To remove the capacity of a list follow the Clear()method call with a call to TrimExcess().
--------------------
CHAPTER-13 (Introduction to ADO.NET)
1. Give the overall concept of ADO.NET.
Answer-
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.
2. Explain in detail ADO.NET architecture.
Answer-
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 set? Explain.
Answer-
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.
4. Write a program to show the demonstration of ADO.NET.
Answer-
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 Intege
Dim conn As New OleDb.OleDbConnection ("Provider=SQLOLEDB;User ID=sa;Password=sql2008;Trusted_Connection=yes;Initial Catalog=CallCenter11;data source=localhost")
con n.Open()
Dim deleteEMP As OleDb.OleDbCommand = New OleDb.OleDbCommand("delete from Employees where EmpID='E003'", con n)
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.
5. What do you mean by ADO.NET data providers? Explain briefly.
Answer-
A .NET data provider is a software library consisting of classes that provide data access services such as connecting to a data source, executing commands at a data source and fetching data from a data source with support to execute commands within transactions. It resides as a lightweight layer between data source and code, providing data access services with increased performance.
The .NET data provider is a component of ADO.NET, a subset of the .NET framework class library.
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.
6. Briefly explain the following ADO.NET objects.
A. the SqlConnectionObject
--To interact with a database, you must have a connection to it. The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the data base. A connection object is used by command objects so they will know which database to execute the command on.
B. the SqlCommandObject
--The process of interacting with a database means that you must specify the actions you want to occur. This is done with a command object. You use a command object to send SQL statements to the database. A command object uses a connection object to figure out which database to communicate with. You can use a command object alone, to execute a command directly, or assign a reference to a command object to an SqlDataAdapter, which holds a set of commands that work on a group of data as
described.
C. the SqlDataReaderObject
--Many data operations require that you only get a stream of data for reading. The data reader object allows you to obtain the results of a SELECT statement from a command object. For performance reasons, the data returned from a data reader is a fast forward-only stream of data. This means that you can only pull the data from the stream in a sequential manner. This is good for speed, but if you need to manipulate data, then a DataSet is a better object to work with.
D. the DataSetObject
--DataSet objects are in-memory representations of data. They contain multiple Datatable objects, which contain columns and rows, just like normal database tables. You can even define relations between tables to create parent-child relationships. The DataSet is specifically designed to help manage data in
memory and to support disconnected operations on data, when such a scenario make sense. The DataSet is an object that is used by all of the Data Providers, which is why it does not have a Data Provider specific prefix.
E. the SqlDataAdapterObject
--Sometimes the data you work with is primarily read-only and you rarely need to make changes to the underlying data source. Some situations also call for caching data in memory to minimize the number of database calls for data that does not change. The data adapter makes it easy for you to accomplish these things by helping to manage data in a disconnected mode. The data adapter fills a DataSet object when reading the data and writes in a single batch when persisting changes back to the database. A data adapter contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the database. Additionally, the data adapter contains command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data. You will have a data adapter defined for each table in a DataSet and it will take care of all communication with the database for you. All you need to do is tell the data adapter when to load from or write to the database.
**Differences between DataSet and DataReader?Answer-Following are some major differences between DataSet and DataReader:
--------------------
CHAPTER-14 (Introduction to ASP.NET)
1. What is a web service ? Explain its working.
Answer-
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.
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 does the web service is different from web page?
Answer-
The differences between a Web service and a Web page are the following-
1.Web Services have No User Interface
but Web Page Has a User Interface.
2.Web Services Interacts with application and Web Page Interacts with the user.
3.Web Services Works with any type of client but Web Page Works with web browser client.
3. What is ASP.NET?
Answer-
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 .
4. What is use of ASP.NET?
Answer-
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.
5. Write a program to display “Welcome to ASP.NET” 8 times in increasing order of their font size using ASP.NET.
Answer-
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:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication9.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body MS_POSITIONING="GridLayout">
<form id="Form2" method="post" runat="server">
<%for(int i=0;i<8;i++){%>
<font size="<%=i%>">Welcome to ASP.NET ChandU</font><br/></font>
<%}%>
</form>
</body>
</html>
6. What is the role of System.Web?
Answer-
The System.Web namespace supplies classes and interfaces that enable browser and server communication. This namespace includes the HttpRequest class that provides extensive information about the current HTTP request, the HttpResponse class that manages HTTP output to the client, and the HttpServerUtility class that provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control.
7. Write a program to demonstrate handling of server control programs.
Answer-
ddlcountry.Items.Add("Bangladesh");
ddlcountry.Items.Add("Bhutan");
ddlcountry.Items.Add("India");
ddlcountry.Items.Add("Nepal");
ddlcountry.Items.Add("Pakistan");
ddlcountry.Items.Add("Sri Lanka");
CompareValidator1.ControlToValidate="txtcpassword";CompareValidator1.ControlToCompare="txtpassword";CompareValidator1.Text="The values of Password and Confirm Password fields does not match";
RequiredFieldValidator1.ControlToValidate="txtuname";RequiredFieldValidator1.Text="Please enter a user name";
RequiredFieldValidator2.ControlToValidate="txtpassword";RequiredFieldValidator2.Text="Please enter a password";
RequiredFieldValidator3.ControlToValidate="txtcpassword";RequiredFieldValidator3.Text="Please re-enter the password";
10. In the Click event of btnsubmit, enter the following code:
if(IsValid)
{
lblmessage.Text="Welcome "+ txtfname.Text +" "+txtlname.Text +
".You have successfully registered.";
}
11. Execute the application.
8. Explain briefly the web services provided by ASP.NET.
Answer-
9. Write a note on ASP.NET class library.
Answer-
The .NET Framework class library is a library of classes, interfaces, and value types that provide access to system functionality. It is the foundation on which .NET Framework applications, components, and controls are built.
--------------------
No comments:
Post a Comment