Académique Documents
Professionnel Documents
Culture Documents
code is sent to the .NET runtime manager. The .NET runtime manager executes the code.
While executing the code, a security check is performed to ensure that the code has the
appropriate permissions for accessing the available resources.
4. Which are the platform technologies supported by .NET Framework?
Ans.
Some of the platform technologies supported by .NET Framework are:
ADO.NET
ASP.NET
VB.NET
Consistent programming model: The base classes of the .NET class library provide
standard functionality such as, input/output, remoting, thread management, string
manipulation, user interface design, and security management. The ADO.NET classes
allow developers to access data in the form of XML. XML classes enable developers to
read, write, manipulate, and transform XML files. The ASP.NET classes support the
development of Web-based applications and Web services. The Windows forms classes
support the development of desktop-based applications. Together, the .NET class library
provides a common functionality to all .NET languages resulting in a consistent object
model regardless of the programming language used by the developer.
Language independence: The .NET developer has the independence to code one module
of an application in one language and the other module of the same application in another
language. This language interoperability can help in code reuse, and improve the
efficiency of the development process.
Ease of application deployment: The .NET Framework manages the details of
locating and loading the components required by an application, even if several versions
of the same application exist on the computer. The .NET Framework ensures that all the
components on which the application depends are available on the computer before the
application begins to run. Visual Studio 2005 includes a new application deployment
technology known as ClickOnce, which allows you to easily deploy a Windows forms
application. ClickOnce enables you to create desktop applications that are deployed with
a secure and system-controlled installation.
Improved security: The .NET Framework provides several mechanisms for protecting
resources and code from unauthorized users:
Code Access Security (CAS) uses permissions to control the code accessing
protected resources and operations.
Ease of creating dynamic Web content: Dynamic Web content is easier to create with
.NET. ASP. NET 2.0 includes various features that enable you to easily develop Web
applications having a consistent layout and appearance.
Visual Studio .NET: Visual Studio .NET is the Microsoft application and interface for
programming in .NET. Visual Studio .NET provides all the programming advantages
mentioned so far. This development environment has an extensive set of ready-to usecontrols, good debugging facilities, easy and simple programming features, and a vast set
of .NET base classes. All these features enable you to develop high performance
applications in a short period of time.
The .NET Framework 2.0 BCL supports backward compatibility with the earlier
versions.
.NET supports C++ because of backward compatibility. To run a C++ code on .Net
Framework, you need to include the following line at the beginning of the code:
#using <mscorlib.dll>
VB applications can work on VB.NET and ASP applications can run on ASP.NET
because of backward compatibility.
You can easily reference COM components in.NET applications.
FAQs
1. What are the different types of application architectures?
Ans: The different types of application architectures are:
Single-tier: A single application handles all functions related to the user, business, and
data service layers. Such an application is also called a monolithic application.
Two-tier: The two-tier architecture divides an application into the following two
components:
The business logic can either be integrated with the client (fat client) or with the server
(fat server).
Three-tier: In the case of three-tier architecture, all the three service layers reside
separately, either on the same machine or on different machines. The user interface
interacts with the business logic. The business logic validates the data sent by the
interfaces and forwards it to the database if it conforms to the requirements. The frontend only interacts with business logic, which, in turn, interacts with the database.
n-tier: An n-tier application uses business objects for handling business rules and data
access. It has multiple servers handling business services. This application architecture
provides various advantages over other types of application architectures. Some of the
advantages include extensibility, resilience to change, maintainability, and scalability of
the application.
Whidbey is the code name of Visual Studio 2005, which was released in November 200
CLR
Ans. The CLR loads and executes the code. Code management is a fundamental
principle of the runtime. It also provides services such as memory management, thread
management, remoting, type safety, code security, and robustness.
Managed code
Ans. The code that is developed with a language compiler that targets the CLR is called
managed code. Managed code is designed to run on .Net environment.
Intermediate language
Ans. In the .NET framework, all the .NET languages get compiled into the MSIL or
simply the Intermediate Language (IL). The intermediate language is analogous to the
byte code of Java. The significant difference is that the byte code is interpreted while the
IL is compiled by JIT compilation to native machine code.
CTS
Ans. The CTS is a standardized set of basic data types. This system provides a way to
language interoperability. An object implemented in one .NET supported language can
call an object implemented in another .NET supported language.
Ans. NET Base Classes is a library consisting of an extensive set of functions for all
services supported by the Framework. This class library provides classes that can be
used in the code to accomplish a range of common programming tasks such as string
management, data collection, database connectivity, and file access.
Assemblies
Ans. Assembly is the unit in which compiled managed code is stored. An assembly
contains IL and metadata. Metadata gives details of the assembly, properties and
methods stored in it, and security information.
CLS
Ans. Common Language Specification (CLS) is a set of rules for basic language features
that have been defined to enhance and ensure language interoperability.
Reflection
Ans. Reflection is the process of obtaining information about assemblies and the types
defined within them as metadata at runtime.
JIT compilation
Ans. JIT compilation converts IL into its native machine code. The name JIT is because
it compiles portion of code as and when required at runtime.
Manifest
Ans.
Manifest is the area of the assembly where metadata is stored.
Application domain
Ans.
Application domain is the boundary that the CLR establishes around objects created within
the same application. Application domain allows different code to run in the same process
space.
Garbage collection
Ans.
The garbage collection feature relieves the programmer from the responsibility of freeing
memory when no longer required. The CLR calls the garbage collector to handle memory
efficiently.
5. What are the functionalities of CLR? Give the steps involved in the managed execution
process.
Ans.
The CLR has the following functionalities:
The CLR uses metadata to locate and load classes, lay out instances in memory, resolve
method invocations, generate native code, enforce security, and set runtime context
boundaries.
The CLR automatically handles object layout and manages references to objects,
releasing them when they are no longer being used. Automatic memory management
eliminates memory leaks as well as some other common programming errors.
The CLR makes it easy to design components and applications whose objects interact
across languages. Objects written in different languages can communicate with each
other, and their behaviors can be tightly integrated.
4.
Defines rules that languages must follow, so that different languages can interact with
each other.
Value types
Reference types
Type
Value Types
Built-In-Value
Types
User-Defined
Value Types
Enumerations
Reference Types
Self Describing
Types
Class Types
User-Defined
Classes
Pointer
Types
Interface
Types
Arrays
Boxed Value
Types
Delegates
Type Classification
Value types directly store data in the variable. Value types can be built-in type, user-defined
types, or enumerations.
Reference types store a reference to the data's memory address. Reference types can be selfdescribing types, pointer types, or interface types. Self-describing types are further split into
arrays and class types. The class types are user-defined classes, boxed value types, and
delegates.
All types derive from the System.Object base type.
9. Write a note on metadata.
Ans.
An assembly stores all the information about itself. This information is called metadata and
includes the name and version number of the assembly, security information, information
about the dependencies, and a list of the files that constitute an assembly. Metadata is the
binary information describing the program.
When we compile our code into a PE file, the metadata is inserted into one portion of the PE
file, while the code is converted to IL and inserted into another portion of the PE file. Every
type member that are defined or referenced in a module is described within metadata. When
code is executed, the runtime loads metadata into memory and refers it to get information
about the code's classes, members, inheritance, and so on.
Metadata allows .NET languages to describe themselves in a language-neutral manner. It
gives required information to the CLR to perform much of its functionalities. The presence of
metadata makes the assembly self-describing file. The CLR modules or components or other
assemblies which want to communicate with each other use this information stored in
metadata to perform their tasks.
10. It is told that if we learn any one .NET language, then working with other .NET
languages will be easy. How? Explain with an appropriate example.
Ans.
It can be told that if you have learned any one .NET language, then working with other .NET
languages will be easy. This is because all the .NET languages rely on the same managed
classes of BCL for the same services. The same classes, methods, parameters, and types are
used for all the system services regardless of any .NET language.
Let us look at the following code that writes to and then reads from a file:
// Program in C#
using System;
using System.IO;
static public void Main()
{
StreamWriter sw1=new StreamWriter("temp.txt", true);
string tempstring="Hi, this is Gopal";
sw1.WriteLine(tempstring);
sw1.Close();
StreamReader sr1=new StreamReader("temp.txt");
string filestring=sr1.ReadToEnd();
sr1.Close();
Console.WriteLine(filestring);
}
// Program in VB.NET
shared public sub Main()
dim sw1 as StreamWriter=new StreamWriter("temp.txt", true)
dim tempstring as string= "Hi, this is Gopal"
sw1.WriteLine(tempstring)
sw.Close()
dim sr1 as StreamReader=new StreamReader("temp.txt")
dim filestring as string=sr1.ReadToEnd()
sr1.Close()
Console.WriteLine(filestring)
end sub
If we see, both versions of the above program are nearly identical. The syntax and use of
StreamReader, StreamWriter, and the Console class are identical, same methods, and identical
parameters.
FAQs
1. What is BCL?
Ans:
The BCL is an object-oriented library of pre-packaged functionality.
2. What is the difference between managed code and managed data?
Ans:
The code that targets the functionalities of the CLR is known as the managed code. C#,
VB.NET, and Jscript.NET code is managed by default. However, C++ code is not managed
by default.
Managed data refers to the data that is allocated and deallocated by the garbage collection
feature of the CLR.
Using the Windows installer. (The installer used must be compatible with the GAC.)
Using the Gacutil.exe that is the GAC tool.
Using the Windows drag and drop feature.
// ABC
// ABC.Class1
Here the ABC.Class1 and XYZ.Class1 are two different types, even if the class name is same.
5. List out the difference between C# and C++.
Ans.
The differences between C# and C++ are as follows.
C#
C# is a purely object-oriented language.
C++
C++ supports object-oriented programming.
C#
C++
C# Vs. C++
FAQs
1. Can you use the using statement with multiple objects?
Ans:
You can use the using statement with multiple objects by nesting using statements, as
shown in the following code snippet:
using (object1);
using (object2);
The above code snippet illustrates the use of nested using statements.
2. Has C# got its own class library?
Ans:
C# has not got its own class library. It uses the class library of the .NET Framework.
3. How will you compile Test1.cs to produce NewFile.exe?
Ans:
You need to type the following command to implement this task:
csc /out:NewFile.exe Test1.cs
Value types: Variables of the value types directly contain their data. With value types,
the variables have their own copy of the data.
Reference types: Variables of the reference types store address of their data. With
reference types, it is possible for two variables to reference the same object.
2. What are variables? How many categories of variables are there in C#? Define each.
Ans.
Variables represent storage locations. Every variable has a type that determines what kind of
data can be stored in the variable.
There are seven categories of variables:
Static variables: A variable declared with the static modifier is called a static variable.
There will be only one copy of the variable, regardless of how many instances of class (in
which static variable exists) are created.
Instance variables: A variable declared without the static modifier is an instance
variable.
Array elements: The array is a container that has a list of storage locations for a
specified type. The elements for a specified type of an array come into existence when an
array instance is created and exists until there are no references to that array instance.
Value parameters: Parameters are arguments passed to the function. A parameter
declared without a ref or out modifier is a value parameter. A value parameter comes into
existence when the function is invoked and is initialized with the value of the argument
passed. A value parameter exists until the function returns.
Reference parameters: A parameter declared with a ref modifier is a reference
parameter. A reference parameter does not create a new instance, it points to the same
storage location of the parameter passed as an argument.
Output parameters: A parameter declared with an out modifier is an output parameter.
The value of an out argument is not passed to the out parameter.
Local variables: A local variable is declared within a block, like a for-statement, a
switch-statement, or a using-statement. A local variable is not automatically initialized
and thus has no default value.
In the above example, a Stack class is implemented as a linked list of Node instances. These
node instances are created in the Push method and are deallocated when no longer in use.
4. Write a note on expressions and operators in C#.
Ans.
An expression is a sequence of operators and operands that specifies computation and assigns
the result to a variable. Expressions are constructed from operands and operators. The
operators of an expression indicate which operations to perform. Examples for operators are
+, -, *, /, etc. Examples for operands are literals, variables, and expressions.
There are three kinds of operators:
Unary operators: The unary operators operate on only one operand. For example, --x,
x++.
Binary operators: The binary operators operate on two operands. For example, x + y.
Ternary operator: The ternary operator operates on three operands. For example,
condition? true_exp: false_exp. There is only one ternary operator, ?:.
5. What are empty statement and labeled statements? Why are they used?
Ans.
An empty statement (;) is used when there are no operations to perform. Execution of an
empty statement simply transfers control to the end point of the statement. For example, an
empty statement can be used when writing a while statement with a null body:
while (WaitForAnEvent())
;
An empty statement can also be used to declare a label just before the closing } of a block:
void Func()
{
...
if (true) goto exit;
...
exit: ;
}
The above example uses the name abc as both a parameter and a label.
6. What is an iterative statement? Explain foreach statement with example.
Ans.
Iteration statements repeatedly execute a block of statements. The number of iterations
depends on the condition represented by the boolean expression. The block of code will be
iterated until the condition is true.
Consider the following code:
using System;
class TestForeach
{
static void Main()
{
int[] array1 = new int[] {1,2,3,4,5};
foreach (int i in array1)
Console.WriteLine(Value is {0}, i);
}
}
In the above example, the foreach statement iterates through the elements of array1.
break statement
continue statement
goto statement
return statement
throw statement
In the above example, the checked keyword allows you to report the overflow at runtime.
9. Give an example of lock and using statements.
Ans.
Example of lock statement:
static void Main()
{
A a = ...;
lock(a) {
a.P = a.P + 1;
}
}
r.Func();
}
}
In the above code snippet, resources are obtained with the using statement.
10. How are structures different from classes in C#?
Ans.
Structures are value types and classes are reference type. A variable of a structure type
directly contains the data of the structure, whereas a variable of a class type contains a
reference to the object. You can inherit classes but you cannot inherit structures.
11. What are interfaces? Give an example.
Ans.
Interfaces are used to define a contract; a class or struct that implements the interface must
obey to this contract. Interfaces can contain methods, properties, indexers, and events as
members. They cannot contain constants, fields (private data members), constructors, and
destructors, or any type of static member. All the members of an interface are public by
definition.
Consider the following example:
interface IExample
{
string this[int index] { get; set; }
event EventHandler E;
void Func(int value);
string P { get; set; }
}
public delegate void EventHandler(object sender, EventArgs e);
The above example shows an interface that contains an indexer, an event E, a method Func,
and a property P.
12. What is a delegate? What is the use of it? Give an example.
Delegates are objects that you use to call the methods of other objects. Delegates are said to
be
object-oriented function pointers since they allow a function to be invoked indirectly by using
a reference to the function.
A delegate declaration defines a class that is derived from the class System.Delegate. A
delegate instance encapsulates one or more methods, each of which is referred to as a callable
entity. For instance methods, a callable entity consists of an instance and a method on that
instance. For static methods, a callable entity consists of just a method. Given a delegate
instance and an appropriate set of arguments, one can invoke all instance methods of that
delegate with that set of arguments.
Consider the following example of a delegate:
class Test
{
static void F()
{
System.Console.WriteLine("Test.F");
}
The above example creates a SimpleDelegate instance, dele, and then immediately calls it.
This program displays Test.F.
13. Write a program to demonstrate the usage of enums in C#.
Ans.
The following program illustrates the use of enums.
enum Color
{
Red,
Blue,
Green
}
class Shape
{
public void Fill(Color color)
{
switch(color)
{
case Color.Red:
Console.WriteLine(RED);
break;
case Color.Blue:
Console.WriteLine(BLUE);
break;
case Color.Green:
Console.WriteLine(GREEN);
break;
default:
break;
}
Console.Read();
}
}
The above program shows a color enum and a method that uses this enum.
14. Write a note on namespaces in C#.
Ans.
C# programs are organized by using namespaces. Namespaces are used both as an internal
organization system for a program, and as an external organization system. This is a way of
writing program elements that are exposed to other programs.
A namespace declaration consists of the keyword namespace, followed by a namespace name
and body:
namespace NamespaceName
{
... // namespace body
}
Classes actually contain data and Namespaces are used to logically arrange classes.
Namespaces can also contain many other Namespaces and classes. C# classes are organized
by using namespaces. Namespaces provide a way to group classes by providing an extra level
of naming beyond the class name.
Namespaces are implicitly public and the declaration of a namespace does not include any
access modifiers. The identifier or name of a namespace may be a single identifier or a
sequence of identifiers separated by . tokens. The latter form permits a program to define a
nested namespace.
Consider the following code snippet:
namespace Example.Namespace1
{
public class NmEx
{
public string Display() {
return "Namespace example";
}
}
}
Namespaces are hierarchical, and the name Example.Namespace1 is an easier and convenient
way for defining a namespace named Example that contains a namespace named
Namespace1, as in:
namespace Example
{
namespace Namespace1
{
}
}
FAQs
1. What will be the value of i in the following code:
for(int i = 0; i < 10 ; i++);
Ans:
The variable i will be initialized to 0, then i will be incremented till its value is less then 10.
At the end of the loop, i will have a value of 10.
Ans:
= is an assignment operator. While checking for values, the comparison operator, ==, has to
be used.
3. What will be the output of the following code:
using System;
namespace ConsoleApplication1
{
class increment
{
static void Main()
{
int x, y, z;
x=5;
y=++x;
z=x++;
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.Read();
}
}
}
Ans:
7
6
6
4. Consider the following code:
string s= Example;
char s1= s[2];
Public, which is selected by including a public modifier in the member declaration. The
intuitive meaning of public is access not limited.
Protected internal (meaning protected or internal), which is selected by including both a
protected and an internal modifier in the member declaration. The intuitive meaning of
protected internal is access limited to this program or types derived from the containing
class.
Protected, which is selected by including a protected modifier in the member declaration.
The intuitive meaning of protected is access limited to the containing class or types
derived from the containing class.
Internal, which is selected by including an internal modifier in the member declaration.
The intuitive meaning of internal is access limited to the program.
Private, which is selected by including a private modifier in the member declaration. The
intuitive meaning of private is access limited to the containing type.
The above example shows a class named Constants that has two public constants.
3. Give an example of field member.
Ans.
Consider the following code, which displays a class and its field members:
class Color
{
internal ushort redPart;
internal ushort bluePart;
internal ushort greenPart;
public Color(ushort red, ushort blue, ushort green)
{
redPart = red;
bluePart = blue;
greenPart = green;
}
public
public
public
public
0xFF);
}
static
static
static
static
readonly
readonly
readonly
readonly
Color
Color
Color
Color
In the above example, the Color class has the fields: redPart, bluePart, greenPart, Red, Blue,
Green, and White.
4. With appropriate examples, explain parameter passing in C#.
Ans.
Parameters can be passed by value or by reference. These are explained as follows:
Passing by value: The parameter modifiers 'ref' and 'out' relate to how the parameter is
passed into the method. By default, parameters are passed by value. In this case, when the
method is called, the value given is copied to the variable specified in the method
declaration. The following example illustrates this point; note that the change made to
variable b in the body of the 'change' method does not result in a change to the variable a
used to invoke the method.
Consider the following code snippet:
public static void Main()
{
int a = 0;
change(a);
Console.WriteLine(a); //Line 2
}
public static void change(int b)
{
b = 5;
Console.WriteLine(b); //Line 1
}
In the above example, the value of a is initialized to 0. When the change method is
called, the value of a is changed to 5. Therefore, Line1 displays 5. However, the
parameter a is passed by value. Therefore the original value of a does not change.
Console.WriteLine(a); //Line2
In the above example, the value of a is initialized to 0. When the change method is called, the
value of a is changed to 5. Therefore, Line1 displays 5. Here, the parameter a is passed by
reference. Therefore the original value of a changes. Therefore, Line2 would display 5.
else
return GetNode(index).Value;
}
set
{
if (!ValidIndex(index))
throw new Exception("Index out of range.");
else
GetNode(index).Value = value;
}
}
...
}
class Test
{
static void Main()
{
Stack s = new Stack();
s.Push(1);
s.Push(2);
s.Push(3);
s[0] = 33; // Changes the top item from 3 to 33
s[1] = 22; // Changes the middle item from 2 to 22
s[2] = 11; // Changes the bottom item from 1 to 11
}
}
The above example shows a Point class provides two public instance constructors, one of
which takes no arguments, while the other takes two arguments.
b. Destructor
Ans.
A destructor is a member that implements the actions required to destroy an instance of a
class. Destructors cannot have parameters, they cannot have accessibility modifiers, and they
cannot be called explicitly. The destructor of an instance is called automatically during
garbage collection.
Consider the example:
using System;
class Point
{
public double x, y;
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
~Point()
{
Console.WriteLine("Destructed {0}", this);
}
public override string ToString()
{
return string.Format("({0}, {1})", x, y);
}
}
The above example shows an Employee class with a static constructor that initializes a static
field.
9. How does C# support inheritance?
Ans.
C# classes support inheritance by using the : operator.
Consider the following example:
using System;
class A
{
public void F() { Console.WriteLine("Inside A.F"); }
}
class B: A
{
public void G() { Console.WriteLine("Inside B.G"); }
}
class Test
{
static void Main()
{
B b = new B();
b.F();
// Inherited from A
b.G();
// Introduced in B
A a = b;
a.F();
// Treat a B as an A
}
}
Ans.
Method overloading refers to the methods with the same name but different signatures doing
different tasks.
Consider the following example:
using System;
class PolymorphismEx
{
public static int add(int a, int b)
{
int sum=a+b;
Console.WriteLine(sum);
}
public static int add(int a, int b, int c)
{
int sum=a+b+c;
Console.WriteLine(sum);
}
static void main()
{
add(3,4);
add(3,4,5);
add(5,6);
}
}
In the above example, the add function is overloaded as the two add functions have different
signatures. The output of the above program is:
7
12
11
11. What is operator overloading? Give an example.
Ans.
Operator overloading refers to loading an operator to perform different operations on different
data types on different contexts. To overload an operator in a class, one defines a method by
using the 'operator' keyword.
The following program uses operator overloading to create a complex number class
ComplexAdd that defines complex addition. The program displays the imaginary and the real
parts of the numbers and the addition result using an override of the ToString method.
// complexAdd.cs
using System;
public struct ComplexAdd
{
public int r;
public int img;
public Complex(int r, int img)
{
this.r = r;
this.img = img;
}
// Declare which operator to overload
Output
First complex number: 5 + 3i
Second complex number: 6 + 2i
The sum of the two numbers: 11 + 5i
FAQs
1. What is constructor chaining?
Ans:
Constructor chaining refers to one constructor being called by another constructor. Consider
the following code snippet:
class ConstrCh
{
private ConstrCh ()
{
Console.Write("1");
}
private ConstrCh (int x):this()
{
Console.Write("2");
}
public ConstrCh (int x, int y):this(10)
{
Console.Write("3");
}
}
class Display
{
public static void Main()
{
In the above program the ConstrCh (int x, int y) invokes the ConstrCh (int x) constructor by
using a special syntax : this(arguments), which in turn invokes the ConstrCh () constructor.
2. How would you implement encapsulation in classes?
Ans:
Access specifiers are used to implement encapsulation in classes. For example, if we want to
make a member variable to be inaccessible from outside the class, we need to declare it
private.
3. Does C# support multiple inheritance?
Ans:
C# does not support multiple inheritance. However, C# supports multiple interfaces.
4. How do you declare a pure virtual function in C#?
Ans:
You can declare a pure virtual function in C# by using the abstract modifier. Consider the
following example:
public abstract void func(int i);
#if
#else
#elif
#endif
#define
#undef
#warning
#error
#line
Ans. A preprocessor manipulates the source code. It breaks up the source code into modules.
Preprocessor directives instruct the preprocessor to perform specific tasks. Some of the
preprocessor directives are explained below.
#if: It begins a conditional directive for testing a symbol, to see if they evaluate to true. If true,
the compiler evaluates all the code between the #if and the next corresponding directive.
#else: It evaluates if none of the expressions in the preceding #if or #elif directives evaluate to
true.
#elif: It evaluates if neither the preceding #if nor any preceding #elif directive expressions
evaluate to true.
#endif: It specifies the end of an #if directive.
#define: It defines a symbol, which can be passed to the #if directive to evaluate the
expression as true.
Consider the following code, which illustrates the use of #if, #else, #elif, #endif, and #define:
#define DEBUG
#define VC_V6
using System;
public class IfClass
{
public static void Main()
{
#if (DEBUG && !VC_V6)
Console.WriteLine("DEBUG
#elif (!DEBUG && VC_V6)
Console.WriteLine("VC_V6
#elif (DEBUG && VC_V6)
Console.WriteLine("DEBUG
#else
Console.WriteLine("DEBUG
defined");
#endif
}
}
Output
DEBUG and VC_V6 has been defined.
#undef: It undefines a symbol. Consider the following code:
#undef DEBUG
using System;
public class Test
{
public static void Main()
{
#if DEBUG
Console.WriteLine("DEBUG has been defined");
#else
Console.WriteLine("DEBUG has not been defined");
#endif
}
}
Output
DEBUG has not been defined.
#warning: It generates a Level 1 warning from a specific location in the code. Consider the
following code snippet:
#define DEBUG
public class Test
{
public static void Main()
{
#if DEBUG
#warning DEBUG defined
#endif
}
}
#error: It generates an error from a specific location in the code. Consider the following code
snippet:
#define DEBUG
public class Test
{
public static void Main()
{
#if DEBUG
#error DEBUG defined
#endif
}
}
#line: It changes the compiler's line number and the file name. Consider the following code
snippet:
public class Test
{
public static void Main()
{
#line 100
int i;
// error or warning will be: CS0168 on line 100
#line 10
char c;
// error or warning will be: CS0168 on line 10
}
}
Exceptions are handled by a try statement. When an exception occurs, the system searches for
the nearest catch block that can handle the exception. Once a matching catch block is found,
the control is transferred to the first statement of the catch block and the catch block executes.
If no matching catch block or finally block is found, then the execution of the thread is
terminated.
Note: If the application does not handle these exceptions, then the application terminates
(default behavior).
3. What is an unsafe code? Explain.
Ans. Unsafe code refers to the code that is processed with low security levels. There are
situations where access to pointer types becomes a necessity. For example, interfacing with
the underlying operating system, accessing a memory-mapped device, or implementing a
time-critical algorithm may not be possible without access to pointers. To address this need,
C# provides the ability to write unsafe code. In unsafe code, it is possible to declare and
operate on pointers, to perform conversions between pointers and integral types, to take the
address of variables, and so forth. In a sense, it is like writing C code within a C# program.
Unsafe code must be clearly marked with the modifier unsafe, so developers cannot possibly
use unsafe features accidentally. When CLR finds this unsafe modifier, the execution engine
works to ensure that the unsafe code cannot be executed in an untrusted environment.
4. What is threading? List out the advantages and disadvantages of multiple threads.
Ans. Threads are the basic unit to which an operating system allocates processor time, and
more than one thread can run inside that process. Each thread maintains exception handlers, a
scheduling priority, and a set of structures the system uses to save the thread context until it is
scheduled. The thread context includes all of the information the thread needs to resume
execution, including the set of CPU registers and stack, in the address space of the thread's
host process.
Multithreading offers the following advantages:
The .NET Framework library base classes are the foundation on which .NET applications,
components, and controls are built. These also include types that perform the following
functions:
The System.Object class provides classes and methods that allow you to build generic
routines, provides Type System Unification, and enables working with groups
collections.
The System.String class provides methods that allow you to perform various string
operations.
The System.Array class provides methods for creating, traversing, manipulating, sorting,
and searching arrays.
The System.Collections namespace contains interfaces and classes that allow you to
define various collections of objects, such as lists, queues, bit arrays, hash tables, and
dictionaries.
7. What are the different methods supported by System.Object class? Give an example for
each.
Ans. The methods are:
Equals: This method of the object class provides a default implementation that compares
two reference type objects for reference equality.
The following code snippet illustrates the use of the Equals method:
public static void Main()
{
string str1= Mark;
string str2= Adam;
str3= Mark;
Console.WriteLine(Object.Equals(str1,str2));
False
Console.WriteLine(Object.Equals(str1,str3));
True
}
//Displays
//Displays
//Displays
GetType: This method returns a Type object, describing the object it was called on.
The following code snippet illustrates the use of the GetType method:
public static void Main()
{
Class1 obj= new Class1();
Console.WriteLine(obj.GetType()); //Displays Class1
}
GetHashCode: This method makes any object usable in a hash table or any hashing
algorithm.
The following code snippet illustrates the use of the GetHashCode method:
public struct Int32
{
public int val;
public override int GetHashCode()
{
return val; //Returns an integer value
}
}
Finalize: This method is used as a destructor. The Finalize destructor is called after the
last reference to an object is released from the memory. The .NET Framework
automatically runs the Finalize destructor to destroy objects in the memory.
The following code snippet illustrates how to override the Finalize method:
~Object();
Boxing refers to the conversion of value types to object types. Consider the following code
snippet:
public static void Main()
{
int var= 21;
object obj=var; //Boxing
}
In the memory, var and obj are represented in the following manner.
Stack
Heap
var
21
obj
int
21
Representation of var and obj in Memory
Unboxing refers to the conversion of object types to value types. Consider the following code
snippet:
public static void Main()
{
int var= 21;
object obj=var; //Boxing
int var2= (int)obj;
}
Stack
Heap
var
21
obj
int
21
var2
21
In the memory, var, obj, and var2 are represented in the following manner.
Representation of var, obj, and var2 in Memory
Ans.
This program is given below:
using System;
namespace ConsoleApplication1
{
class Change
{
static void Main()
{
string errString = "rose is a rose";
string correctString = errString.Replace("r", "R");
Console.WriteLine(correctString);
Console.ReadLine();
}
}
}
This array contains the elements from arr[0] to arr[4]. The new operator is used to create the
array and initialize the array elements to their default values. In this case, all the array
elements are initialized to zero.
An array that stores string elements can be declared in the same way. For example:
string[] myStringArray = new string[6];
b. Multidimensional arrays
Ans.
Multidimensional array is defined as an array having more than one dimension. For example,
the following declaration creates a two-dimensional array of four rows and two columns:
int[,] arr = new int[4,2];
The following code creates an array of three dimensions, 4, 2, and 3, as shown below:
int[,,] arr = new int [4,2,3];
c. Jagged arrays
Ans.
A jagged array is an array whose elements are arrays. The elements of a jagged array can be
of different dimensions. The following is a declaration of an array that has three elements,
each of which is a
single-dimensional array of integers:
int[][] myJaggedArr = new int[3][];
Before we can use myJaggedArr, its elements must be initialized. We can initialize the
elements like:
myJaggedArr [0] = new int[5];
Each of the elements is a single-dimensional array of integers. The first element is an array of
5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.
It is also possible to use initializers to fill the array elements with values, in which case we do
not need the array size. For example:
myJaggedArr [0] = new int[] {1,3,4,7,9};
myJaggedArr [1] = new int[] {0,2,9,6};
myJaggedArr [2] = new int[] {18,22};
An out parameter of an array type must be assigned before it is used; that is, it must be
assigned by the callee.
For example:
public static void MyMethod(out int[] arr)
{
arr = new int[10];
// definite assignment of arr
}
FAQs
1. How do you define your own exception classes?
Ans:
You can define your own exception classes by deriving the exception classes from the
System.Exception class. Consider the following code snippet:
using System;
public class NameNotFound: Exception
{
:
}
In the above code snippet, the NameNotFound exception class is derived from the
Exception class.
2. What will be the output of the following code:
using System;
namespace ConsoleApplication1
{
class Test
{
static void Main()
{
int a=5;
int b=5;
Console.WriteLine(a==b);
Console.WriteLine(a.Equals(b));
string str1 = "abc";
string str2 = "abc";
Console.WriteLine( str1 == str2 );
Console.WriteLine( str1.Equals(str2) );
Console.Read();
}
}
}
Ans:
True
True
True
True
3. How do you compare two strings by ignoring their case?
Ans:
You can do a case-insensitive string comparison by using the String.Compare function. This
function takes three parameters. The first two parameters are the strings that are to be
compared. The third parameter takes a boolean value, which specifies whether the case is to
be ignored or not.
Consider the following code snippet:
String.Compare(abc,ABC,true) //Returns true
The above code snippet displays true because the third parameter is set to true.
Ans.
ActiveX Data Objects for the .NET Framework (ADO.NET) is a set of classes that provide
data access services to the .NET programmer. ADO.NET provides a rich set of components
for creating distributed, data-sharing applications. It is an integral part of the .NET
Framework, providing access to relational database, XML, and application data.
ADO.NET supports a variety of development needs, including the creation of front end
database clients and middle tier business objects used by applications, tools, languages, or
Internet browsers. ADO.NET provides consistent access to data sources such as Microsoft
SQL Server, or data sources exposed via OLE DB and XML. Data sharing applications can
use ADO.NET to connect to these data sources and retrieve, manipulate, and update data.
The data residing in a database is retrieved through data provider. Different components of the
data provider retrieve data from the database, provide the data to the Visual Basic .NET
application, and update the database with the changes made in the application.
An application can access data either through a dataset or through a DataReader object:
Using a dataset: In this case, the data is cached in a dataset and the application accesses
the data from the dataset.
Using a data reader: In this method, a DataReader object, which is a component of the
data provider, uses the Connection object to connect to the database, uses the Command
object to retrieve data, and provides data to the application in a read-only and forwardonly mode.
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.
In the code given for the Click event of the Delete button, a connection object conn is
created by providing the information about the provider, the data source server, database
name that is to be accessed, and the ID and password for connecting to the data source. Then,
the connection with the database is opened and a DataCommand object deleteEMP is created
from the OleDbCommand class. The DataCommand object deleteEMP is initialized by setting
the SQL statement to be executed using the Connection object conn. Then, the command is
executed and the number of rows affected by the execution of the command is stored in an
integer result.
FAQs
1. What is the difference between a typed and an untyped dataset?
Ans: Typed and untyped dataset are compared in the following table.
Typed Dataset
Untyped Dataset
2. What is data binding? How many types of data binding are there?
Ans: After the data is retrieved from the database, it has to be bound to a control on a
Windows Form to be displayed in a customized format. Such a binding is termed as data
binding. Data binding is of two types:
Simple data binding: It is the process of binding a control, such as a text box or a label,
to a value in a dataset. The dataset value can be bound to the control by using the
properties of the control. For example, you can bind the value of the Name column in the
dataset to a TextBox control by setting the Text property under the DataBindings
category of the TextBox control.
Complex data binding: It is the process of binding a component, such as a DataGrid or a
ListBox control, to display multiple values for a column from the dataset rows.
Multiple Active Result Sets (MARS): In the earlier versions of SQL Server, database
applications could not maintain multiple active statements on a connection. When using
SQL Server default result sets, the applications had to process or cancel all result sets
from one batch before it could execute any other batch on that connection. MARS is a
new feature supported by Visual Studio 2005 that allows you to:
Have more than one pending request under a given SQL Server connection.
Batch updates: In the earlier versions of ADO.NET, a DataAdapter could send only one
SQL statement at a time to the server. This hindered faster updates to the database. To
address this issue, ADO.NET 2.0 now supports batch updates. Batch support in
ADO.NET 2.0 allows a DataAdapter to group insert, update, or delete operations from a
DataSet or DataTable to the server, instead of sending one operation at a time. A
significant benefit of batch updates is that there are fewer round trips to the database
server if you have a large number of rows to update. Batch updates are supported for the
.NET data providers for SQL Server (SqlClient) and Oracle (OracleClient).
When you need to work with a large number of tables, you should use a data reader. If the
number of tables is less, you should use a dataset. If multiple users use the database and the
database needs to be updated frequently, you should use a data reader.
Request
Client
Application
Web
Service
Response
The functionality exposed by a Web service can be accessed by applications by using Internet
standards, such as Simple Object Access Protocol (SOAP). SOAP is a protocol that uses
extensible Markup Language (XML) to describe data and HyperText Transfer Protocol
(HTTP) to transmit application data. An application that uses a Web service is called a Web
service client. The client sends a request to the Web service. The cloud in the figure refers to
the Internet. If the Web service calls some other service to get the answer or response, the
Web service can take a while to respond. While it is waiting for the response, the client can
perform other operations.
2. How is a Web service different from a Web page?
Ans. The differences between a Web service and a Web page are listed in the following
table.
Web Services
Web Page
No User Interface
3. With a neat diagram, explain the event handling process of Web forms.
Ans. Consider a Web form with a button. If a user clicks the button control, an event
Click is raised for the button on the client computer. However, the browser does not
process the event. Instead, the browser raises a postback event so that the Web server
is alerted about the Click event being raised. Next, the event handler written for the
Click event is processed on the Web server and the output is sent to the client
computer.
4. What is ASP.NET?
Ans. ASP.NET is a framework for developing high performance Web applications. It is
a compiled,
.NET-based environment. You can write applications in any .NET compatible language,
including VB.NET, C#, and JScript .NET. Additionally, the entire .NET Framework is
available to any ASP.NET application
5. What is the use of ASP.NET?
Ans. ASP.NET provides a new programming model and infrastructure for more secure,
scalable, and stable applications. You can write applications in any .NET compatible
language, including VB.NET, C#, and JScript .NET. Developers can easily use the
benefits of these technologies, which include the managed CLR environment, type
safety, inheritance, and so on.
ASP.NET has been designed to work seamlessly with What You See Is What You Get
(WYSIWYG) HTML editors and other programming tools, including Microsoft Visual Studio
.NET. Not only it makes Web development easier, but it also provides all the benefits that
tools offer, including a GUI that developers can use to drop server controls onto a Web page
and fully integrated debugging support.
6. Write a program to display Welcome to ASP.NET 8 times in increasing order of their
font size by using ASP.NET. by using ASP.NET.
Ans.
The following program displays Welcome to ASP.NET eight times in increasing order of
their font size.
In the following code, the Web application name WebApplication9 is application specific:
<%@ 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 ASHISH</font><br/></font>
<%}%>
</form>
</body>
</html>
Label
Text
First Name
TextBox
Label
Last Name
User Name
Password
Confirm Password
Address
lbladdress
txtaddress
City
TextBox
Label
lblcpassword
txtcpassword
TextBox
Label
lblpassword
txtpassword
TextBox
Label
lbluname
txtuname
TextBox
Label
lbllname
txtlname
TextBox
Label
lblfname
txtfname
TextBox
Label
ID
lblcity
txtcity
State
lblstate
Control Type
Text
TextBox
Label
txtstate
Postal Code
TextBox
Label
Country
lblcountry
ddlcountry
Telephone no.
TextBox
Label
lblpcode
txtpcode
DropDownList
Label
ID
lbltelno
txttelno
E-mail Id
lblemail
TextBox
txtemail
Label
lblmessage
Button
Submit
btnsubmit
6.
7.
8.
9.
The text boxes for Password and Confirm Password fields need to display asterisks (*)
when a user enters a value. To enable this, set the TextMode property of these two text
boxes to Password in the Properties window.
Add three RequiredFieldValidator controls to the WebForm1.aspx form by using the
Web Forms tab of the Toolbox.
Add one CompareValidator control to the WebForm1.aspx form by using the Web
Forms tab of the Toolbox.
Double-click the WebForm1.aspx form to open the code-behind file with a .cs
extension. In the Load event of the page, enter the following lines of code:
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";
FAQs
1. Where does the Web page belong in the .NET Framework class hierarchy?
Ans:
System.Web.UI
2. What is a session cookie? How is it different from a persistent cookie?
Ans:
A session cookie, exist in the memory space of a browser. When the browser is closed, all
session cookies added to the browser are lost. A persistent cookie is saved as a text file in the
file system of the client computer.
3. Differentiate between Application_OnStart and Application_OnEnd events.
Ans:
The Application_OnStart event is triggered when an application starts. If you want a script to
be executed as soon as the application starts, you should add it to the Application_OnStart
event. This event is triggered only when the application starts, and is not triggered again until
the IIS service is stopped, the Global.asax file is modified, or the application is unloaded.
The Application_OnEnd event is triggered when an application ends. An application ends
when the Web server is shut down.
4. What is a virtual directory?
Ans:
A virtual directory is the main directory of a Website. This virtual directory contains all the
files, subdirectories, script pages, HTML pages, programs, graphics, and other resources of a
Website. Every Website needs to have a virtual directory and the virtual directory might
contain subdirectories within it.
5. What is a Master page?
Ans:
A Master page sets the standard layout and required content that you want to appear on all the
pages. A Master page includes named regions or content placeholders for which Content
pages provide custom content. A Content page is an .aspx file. It identifies only its Master
Page and the necessary content to fill the placeholders specified in the Master Page.
A Web application should have a consistent layout and appearance. The structure of the
various pages of the application should not be different. However, if the application is large
and multiple people contribute to its development and maintenance, this consistency is
difficult to ensure. ASP.NET 2.0 now provides a solution to this by giving developers an
option to create Master pages.
ASP.NET based Web services can only be accessed over HTTP, whereas the .NET
Remoting can be used across any protocol.
Web services work in a stateless environment where each request results in a new object
created to service the request. .NET Remoting supports state management options and
can identify multiple calls from the same client.
Web services serialize objects through XML contained in the SOAP messages and can
thus only handle items that can be fully expressed in XML. .NET Remoting relies on the
existence of the metadata within assemblies that contain information about data types.
This limited metadata information is passed about an object, when it is passed by
reference.
Web services support interoperability across platforms and are good for heterogeneous
environments. .NET Remoting requires the clients to be by built using .NET, which
means a homogeneous environment.
DCOM relies on a proprietary binary protocol that not all object models support. It also
wants to communicate over a range of ports that are typically blocked by firewalls.
However, .NET Remoting supports different transport protocol formats and
communication protocols. This allows .NET Remoting to be adaptable to the network
environment in which it is being used.
The primary function of remoting is to communicate between server and client by using
objects. After the client is configured properly, a new instance of the remote object is created.
Proxy objects are used by the remoting system. Proxies are those objects that present
themselves as some other objects. The infrastructure of remoting creates proxy objects when a
user generates an instance of remote types. To the user, this proxy object will look exactly
similar to the remote objects. In this proxy object, the user calls a method and the call is
received by the remoting system. The method is then routed to the server and it invokes the
server object. After invoking the server object, a value is returned that is sent back to the
client proxy. This will provide the results to the user.
The communication between server and client is done by using a channel. A channel carries
the data stream, makes a package related to a particular protocol, and sends the package to a
different computer. In remoting architecture, the process of remoting is designed considering
the security factor.
The remoting process is illustrated in the following figure.
Remoting System
Remoting System
Proxy
Server Object
Client Object
Channel
Carries a stream of data, makes a package related to a
particular protocol, and sends the package to a different
computer.
Remoting Process
5. Explain the steps or phases involved in implementing .NET remoting applications.
Ans.
The phases involved in implementing .NET remoting applications are:
1.
2.
3.
System;
System.Runtime;
System.Runtime.Remoting;
System.Runtime.Remoting.Channels;
System.Runtime.Remoting.Channels.Tcp;
System.IO;
RemoteTest;
namespace Server
{
class ClassServer
{
static void Main(String[] args)
{
TcpServerChannel channel = new
TcpServerChannel(9932);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(T
estLoader),
"TestLoader",
WellKnownObjectMode.SingleCall);
System.Console.WriteLine("Hello From Server");
System.Console.ReadLine();
}
}
}
System;
System.Runtime.Remoting;
System.Runtime.Remoting.Channels;
System.Runtime.Remoting.Channels.Tcp;
using RemoteTest;
namespace Client
{
class ClassClient
{
static void Main(string[] args)
{
try
{
ChannelServices.RegisterChannel(new
TcpClientChannel());
TestLoader loader =
(TestLoader)Activator.GetObject(
typeof(RemoteTest.TestLoader),
"tcp://localhost:9932/TestLoader");
string res = loader.Test();
Console.WriteLine("Hello From "+ res);
}
catch(Exception e)
{
Console.WriteLine("Unable to get remote
reference" + e);
}
System.Console.ReadLine();
}
}
}
FAQs
1. How are COM objects accessed from the .NET Framework?
Ans:
COM objects are accessed from the .NET Framework by the use of a Runtime Callable
Wrapper (RCW). The RCW converts the COM interfaces into .NET compatible interfaces.
2. What is serialization? How is it different from deserialization? What are the two
serialization technologies?
Ans:
Serializing is the method in which the state of an object is converted into a form that can be
transported.
Deserialization is a process in which a stream is converted to an object.
The following two serializing technologies are included in the .NET Remoting Framework:
XML serialization: It does not preserve the state of an object and serializes the public
properties alone. This serialization is useful when you want to offer or consume data
without limiting the application that uses the data.
3. What is a channel? What are the different types of channels? How would you initialize a
server channel at port 9932, and then register the channel with the channel services?
Ans:
Channels transport messages between remote objects. If a client activates a method on a
remote object, the information related to the call is transported through the channel to the
remote object. The results from the call are given back to the client in a similar manner. A
client can choose the registered channels on the server to communicate with the remote
object. The different types of channels are:
HTTP channel: The HTTP channel uses the SOAP protocol to transport messages. The
messages that are passed through the SOAP formatter are converted into XML, and
serialized. The necessary SOAP headers are included in the stream. The HTTP channel
can also be configured with the help of binary formatter. HTTP channel that uses binary
formatter are not the same as TCP channel due to the difference between underlined
protocols.
TCP channel: The Transmission Control Protocol (TCP) channel uses a binary formatter
in which the messages are serialized to binary stream. By using the TCP protocol, the
stream is transported to the URI target. The channel provides communication through
TCP sockets.
To initialize a server channel at port 9932, and then register the channel with the channel
services, you would need to use the following code snippet:
TcpServerChannel channel = new TcpServerChannel(9932);
ChannelServices.RegisterChannel(channel);
4. What is activation?
Ans:
Activation is a process in which the object is loaded into memory so that the object is in a
running state. The types of activation are:
Server activation: When the activation process occurs from the server then the activation
is said to be server activation.
Client activation: When the activation process is from the client side then the activation
is said to be client activation.
Remote object activation: When the client activates the object that resides on the server
then the activation is said to be remote object activation.
5. What is MTS?
Ans:
MTS is a component-based transaction processing system for developing, deploying, and
administering server applications. The shift from single-tier to multi-tier environment can be
done easily by using MTS. It provides infrastructure for building scalable and robust
enterprise applications. The application infrastructure includes the services that manage
resources and transactions. In a multi-user environment, the application infrastructure
includes the services that enable multi-users to simultaneously access services and underlying
data.