0% found this document useful (0 votes)
82 views

Dot Net Notes 1

The .NET platform provides a set of technologies and tools for building distributed web applications. It includes the .NET Framework, which consists of the Common Language Runtime (CLR) and class library. The CLR handles execution of code and provides services like memory management and security. Code is compiled to Microsoft Intermediate Language (MSIL) for cross-platform execution. The Just-In-Time (JIT) compiler converts MSIL to native code. Assemblies are fundamental deployment units that contain code and metadata. The Global Assembly Cache (GAC) stores shared assemblies. The garbage collector automatically manages memory.

Uploaded by

Rutik Dak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Dot Net Notes 1

The .NET platform provides a set of technologies and tools for building distributed web applications. It includes the .NET Framework, which consists of the Common Language Runtime (CLR) and class library. The CLR handles execution of code and provides services like memory management and security. Code is compiled to Microsoft Intermediate Language (MSIL) for cross-platform execution. The Just-In-Time (JIT) compiler converts MSIL to native code. Assemblies are fundamental deployment units that contain code and metadata. The Global Assembly Cache (GAC) stores shared assemblies. The garbage collector automatically manages memory.

Uploaded by

Rutik Dak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

What is the Microsoft.NET?

.NET is a set of technologies designed to transform the internet into a full scale distributed platform.
It provides new ways of connecting systems, information and devices through a collection of web
services. It also provides a language independent, consistent programming model across all tiers of
an application.

The goal of the .NET platform is to simplify web development by providing all of the tools and
technologies that one needs to build distributed web applications.

What is the .NET Framework?


The .NET Framework is set of technologies that form an integral part of the .NET Platform. It is
Microsoft's managed code programming model for building applications that have visually stunning
user experiences, seamless and secure communication, and the ability to model a range of business
processes.

The .NET Framework has two main components: the common language runtime (CLR) and .NET
Framework class library. The CLR is the foundation of the .NET framework and provides a common
set of services for projects that act as building blocks to build up applications across all tiers.

What is CLR?
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR.
The CLR can be compared to the Java Virtual Machine or JVM in Java. CLR handles the execution of
code and provides useful services for the implementation of the program. In addition to executing
code, CLR provides services such as memory management, thread management, security
management, code verification, compilation, and other system services. It enforces rules that in turn
provide a robust and secure execution environment for .NET applications.

What is CTS?
Common Type System (CTS) describes the datatypes that can be used by managed code. CTS defines
how these types are declared, used and managed in the runtime. It facilitates cross- language
integration, type safety, and high performance code execution. The rules defined in CTS can be used
to define your own classes and values.

What is CLS?

PGDAC-MS.Net Page 1
Common Language Specification (CLS) defines the rules and standards to which languages must
adhere to in order to be compatible with other .NET languages. This enables C# developers to inherit
from classes defined in VB.NET or other .NET compatible languages.
CLR and CTS advantages
Language interoperability
Code reusability
Faster development.

What is managed code?


The .NET Framework provides a run-time environment called the Common Language Runtime,
which manages the execution of code and provides services that make the development process
easier. Compilers and tools expose the runtime's functionality and enable you to write code that
benefits from this managed execution environment. The code that runs within the common
language runtime is called managed code.

What is MSIL?
When the code is compiled, the compiler translates your code into Microsoft intermediate language
(MSIL). MSIL is understood by any environment where .Net framework is installed i.e.write once run
anywhere. It is platform independent. MSIL is a part of assembly. The common language runtime
includes a JIT compiler for converting this MSIL then to native code.

MSIL contains metadata that is the key to cross language interoperability. Since this metadata is
standardized across all .NET languages, a program written in one language can understand the
metadata and execute code, written in a different language.
What is JIT?
JIT(Just in time) is a compiler that converts MSIL to native code JIT is a part of CLR. The nativecode
consists of hardware specific instructions that can be executed by the CPU.

Rather than converting the entire MSIL (in a portable executable[PE]file) to native code, the JIT
converts the MSIL as it is needed during execution. This converted native code is stored so that it is
accessible for subsequent calls. This quality makes it faster compiler.

What is portable executable (PE)?


PE is the file format defining the structure that all executable files (EXE) and Dynamic Link Libraries
(DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the
Microsoft Common Object File Format (COFF). The EXE and DLL files created using the
.NET Framework obey the PE/COFF formats and also add additional header and data sections tothe
files that are only used by the CLR.

What is an application domain?


Application domain is the boundary within which an application runs. A process can contain multiple
application domains. Application domains provide an isolated environment to applications that is
similar to the isolation provided by processes. An application running inside one application domain
cannot directly access the code running inside another application domain. To access the code
running in another application domain, an application needs to use a proxy.

PGDAC-MS.Net Page 2
How does an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE.
When you run a .NET application from the command-line, the host is the Shell. The Shellcreates a
new AppDomain for every application. AppDomains can also be explicitly created by
.NET applications.

What is an assembly?
An assembly is a collection of one or more .exe or dll’s. An assembly is the fundamental unit for
application development and deployment in the .NET Framework. An assembly contains a collection
of types and resources that are built to work together and form a logical unit of functionality. An
assembly provides the CLR with the information it needs to be aware of type implementations.

What are the contents of assembly?


A static assembly can consist of four elements:

1.Assembly manifest - Contains the assembly metadata. An assembly manifest contains the
information about the identity and version of the assembly. It also contains the information
required to resolve references to types and resources.
2.Type metadata - Binary information that describes a program.
Microsoft intermediate language (MSIL) code.
A set of resources.

What are the different types of assembly?


Assemblies can also be private or shared. A private assembly is installed in the installation directory
of an application and is accessible to that application only. On the other hand, a shared
assembly is shared by multiple applications. A shared assembly has a strong name and is installed in
the GAC.

We also have satellite assemblies that are often used to deploy language-specific resources for an
application.

What is a dynamic assembly?


A dynamic assembly is created dynamically at run time when an application requires the types
within these assemblies.

What is a strong name?

PGDAC-MS.Net Page 3
You need to assign a strong name to an assembly to place it in the GAC and make it globally
accessible. A strong name consists of a name that consists of an assembly's identity (text name,
version number, and culture information), a public key and a digital signature generated over the
assembly. The .NET Framework provides a tool called the Strong Name Tool (Sn.exe), which allows
verification and key pair and signature generation.

What is GAC? What are the steps to create an assembly and add it to the GAC?
The global assembly cache (GAC) is a machine-wide code cache that stores assemblies specifically
designated to be shared by several applications on the computer. You should share assemblies by
installing them into the global assembly cache only when you need to.
Steps
- Create a strong name using sn.exe tool eg: sn -k mykey.snk
- in AssemblyInfo.cs, add the strong name eg: [assembly: AssemblyKeyFile("mykey.snk")]
- recompile project, and then install it to GAC in two ways :
· drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly)
(shfusion.dll tool)
· gacutil -i abc.dll

What is a garbage collector?


One of the very important services provided by CLR during application execution is automatic
memory management(allocation and deallocation of memory). In this service, garbage collector
plays an important role, it is a back ground thread that performs periodic checks on the managed
heap to identify objects that are no longer required by the program and removes them from
memory. When a program starts, the system allocates some memory for the program to get
executed.
When a C# program instantiates a class, it creates an object.
The garbage collector starts cleaning up only when there is not enough room on the heap to
construct a new object.
The stack is automatically cleared at the end of a method. The CLR takes care of this and you
don’t have to worry about it.
The heap is managed by the garbage collector.
The garbage collection consists of three phases:
1.In the marking phase, a list of all objects in use is created by following the references from all the
root objects, i.e. variables on stack and static objects. Any allocated objects not on the list become
candidates to be deleted from the heap. The objects on the list will be relocated in the compacting
phase if necessary, to compact the heap and remove any unused memory between them.
2.In the relocation phase, all references to remaining objects are updated to point to the new
location of objects to which they will be relocated in the next phase.
3.In the compacting phase, the heap finally gets compacted as all the objects that are not in use any
more are released and the remaining objects are moved accordingly. The order of remaining objects

PGDAC-MS.Net Page 4
in the he ap stays intact.

How value types get collected v/s reference types?


Value types are gets stored on the stack and therefore it gets removed from the stack by its popmethod
when application is done with its use. Reference types get stored on heap so gets collected by garbage
collector.

Dispose v/s Finalize

Dispose Finalize

It is used to free unmanaged resources at any It can be used to free unmanaged resources held by
time. an object before that object is destroyed.

It is called by user code and the class which is


implementing dispose method, must has to It is called by Garbage Collector and cannot be
implement IDisposable interface. called by user code.

It is implemented by implementing IDisposable


interface Dispose() method. It is implemented with the help of Destructors

There is performance costs associated with Finalize


There is no performance costs associated with method since it doesn’t clean the memory
Dispose method. immediately and called by GC automatically.

How to Force Garbage Collection?


You can force this by adding a call to GC.Collect.

What is Finalizer?
inalizers (which are also called destructors) are used to perform any necessary final clean-up
when a class instance is being collected by the garbage collector.
Remarks
• Finalizers cannot be defined in structs. They are only used with classes.
• A class can only have one finalizer.
• Finalizers cannot be inherited or overloaded.
• Finalizers cannot be called. They are invoked automatically.

PGDAC-MS.Net Page 5
• A finalizer does not take modifiers or have parameters.

This means that the Finalize method is called recursively for all instances in the inheritance
chain, from the most-derived to the least-derived.
The programmer has no control over when the finalizer is called because this is determined by
the garbage collector.
Explicit release of resources
If your application is using an expensive external resource, we also recommend that you
provide a way to explicitly release the resource before the garbage collector frees the object.
You do this by implementing a Dispose method from the IDisposable interface that performs the
necessary cleanup for the object. This can considerably improve the performance of the
application. Even with this explicit control over resources, the finalizer becomes a safeguard to
clean up resources if the call to the Dispose method failed.\

Explain the execution cycle of DotNet Application.

1.Sorce code is compiled by language specific compilers.


2.After first compilation, assembly(exe/dll) is created, which is a logical unit of
deployment.
3.Assembly is deployed on CLR for actual execution
4.Loader is responsible for loading and initializing assemblies, modules, resources, and types. When
you run a .NET application on one of these systems that have an updated OS loader, the OS loader
recognizes the .NET application and thus passes control to the CLR.
5.Code Verifier: The key here is type safety, and it is a fundamental concept for codeverification
in .NET. Within the VES, the verifier is the component that executes at runtime to verify that the
code is type safe. Note that this type verification is done at runtime and that this is a fundamental
difference between .
1.The metadata is well formed, meaning the metadata must be valid.
PGDAC-MS.Net Page 6
2.The IL code is type safe, meaning type signatures are used correctly.
Both of these criteria must be met before the code can be executed because JIT compilation will
take place only when code and metadata have been successfully verified.
6.JIT Compiler: JIT compilers play a major role in the .NET platform because all .NET PE files
contain IL and metadata, not native code. The JIT compilers convert IL to native code so that it
can execute on the target operating system. For each method that hasbeen successfully verified
for type safety, a JIT compiler in the CLR will compile the method and convert it into native code.

WHAT IS DELEGATE?
A delegate is reference type that basically encapsulates the reference of methods. It is a similarto
class that store the reference of methods which have same signature as delegate has.
It is very similar to a function pointer in C++, but delegate is type safe, object oriented and
secure as compare to C++ function pointer.

WHY DO WE USE DELEGATE?


1.It is used for type safety.2.For executing multiple methods through one execution. 3.It allows us to pass
methods as parameter. 4.For asynchronous programming. 5.For Call back method implementation.
6.It is also used when working with event based programming. 7.When creating anonymous method.
8.When working with lambda expression.

HOW MANY TYPES OF DELEGATE IN C#?


1.Simple/Single Delegate2.Multicast Delegate3.Generic Delegate

WHAT ARE THE WAYS TO CREATE AND USE DELEGATE?


1.Declare a delegate type. 2.Create or find a method which has same type of signature. 3.Create
object/instance of delegate 4.Pass the reference of method with delegate instance. 5.At last Invoke the
delegate object.

WHAT IS SINGLE DELEGATE?


When Delegate takes reference with single method only then it is called Single Delegate. It isused
for invocation of only one reference method.

WHAT IS MULTICAST DELEGATE?


When Delegate takes reference with multiple methods then it is called multicast delegate. It is used
for invocation of multiple reference methods. We can add or remove references of multiple
methods with same instance of delegate using (+) or (-) sign respectively. It need to consider here
that all methods will be invoked in one process and that will be in sequence.

WHAT IS MULTICAST DELEGATE


When Delegate takes reference with multiple methods then it is called multicast delegate. It is used
for invocation of multiple reference methods. We can add or remove references of multiple
methods with same instance of delegate using (+) or (-) sign respectively. It need to consider here
PGDAC-MS.Net Page 7
that all methods will be invoked in one process and that will be in sequence.

HOW TO ACHIEVE CALLBACK IN DELEGATE?


Callback is term where a process is going on and in between it targets some achievement thenit
return to main method. For callback, we just need to encapsulate the method with delegate.

objCallBackMethodExample.CheckEvenEvent += new OnEvenNumberHandler(objCallBackMeth


odExample.CallBackMethod);

When we are going to call this method using Delegate for callback, only need to pass this
method name as a reference.

HOW TO ACHIEVE ASYNC CALLBACK IN DELEGATE?


Async callback means, process will be going on in background and return back when it will be
completed. In C#, Async callback can be achieved using AsyncCallback predefined delegate as
following.
public delegate void AsyncCallback(IAsyncResult ar);

What are events?


Events are higher level of encapsulation over delegates. Events use delegates internally.
Delegates are naked and when passed to any other code, the client code can invoke the
delegate. Event provides a publisher / subscriber mechanism model.
Create a delegate and declare the event for the same.
public delegate void CallEveryone();
public event CallEveryone MyEvent;
Raise the event.
MyEvent();
Attached client methods to the event are fired / notified.
obj.MyEvent += Function1;

Difference between delegate and events: -


They cannot be compared because one derives from the other.
1.Actually, events use delegates in bottom. But they add an extra layer of security on the
delegates, thus forming the publisher and subscriber model.
2.As delegates are function to pointers, they can move across any clients. So any of the
clients can add or remove events, which can be confusing.

What are attributes?


Attributes provide a powerful method of associating metadata, or declarative information, with code
(assemblies, types, methods, properties, and so forth). After an attribute is associated with a
program entity, the attribute can be queried at run time by using a technique called reflection.

PGDAC-MS.Net Page 8
Attributes have the following properties:
• Attributes add metadata to your program. Metadata is information about the types
defined in a program.
• You can apply one or more attributes to entire assemblies, modules, or smaller program
elements such as classes and properties.
• Attributes can accept arguments in the same way as methods and properties.
• Your program can examine its own metadata or the metadata in other programs by using
reflection.
There are two types of attributes:
1. Predefined attributes: these are provided by FCL. Ex. Obsolete, Serializable,
Conditional etc.
2. Custom attributes: these are developed by developers as per the requirements.
Note: All the attributes are derived directly or indirectly from System.Attribute class.

How to create custom attributes?


The primary steps to properly design custom attribute classes are as follows:
1.Applying the AttributeUsageAttribute 2.Declaring the attribute class 3.Declaring constructors
4.Declaring properties

Applying the AttributeUsageAttribute


A custom attribute declaration begins with the System.AttributeUsageAttribute, which defines some
of the key characteristics of your attribute class. For example, you can specify whether your
attribute can be inherited by other classes or specify which elements the attribute can be applied to.
The following code fragment demonstrates how to use the AttributeUsageAttribute.
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
The AttributeUsageAttribute has three members that are important for the creation of custom
attributes: AttributeTargets, Inherited, and AllowMultiple.

AttributeTargets Member
In the previous example, AttributeTargets.All is specified, indicating that this attribute can be
applied to all program elements. Alternatively, you can specify AttributeTargets.Class, indicating
that your attribute can be applied only to a class, or AttributeTargets.Method, indicating that
your attribute can be applied only to a method. All program elements can bemarked for
description by a custom attribute in this manner.
You can also pass multiple AttributeTargets values. The following code fragment specifies
that acustom attribute can be applied to any class or method.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]

Inherited Property
The AttributeUsageAttribute.Inherited property indicates whether your attribute can be
inherited by classes that are derived from the classes to which your attribute is applied. This
property takes either a true (the default) or false flag. In the following

PGDAC-MS.Net Page 9
AllowMultiple Property
The AttributeUsageAttribute.AllowMultiple property indicates whether multiple instances ofyour
attribute can exist on an element. If set to true, multiple instances are allowed; if set to false(the
default), only one instance is allowed.
If both the AllowMultiple property and the Inherited property are set to true, a class that is inherited
from another class can inherit an attribute and have another instance of the same attribute applied in the
same child class. If AllowMultiple is set to false, the values of any attributes in the parent class will be
overwritten by new instances of the same attribute in thechild class.

Declaring the Attribute Class


After you apply the AttributeUsageAttribute, you can begin to define the specifics of your attribute.
The declaration of an attribute class looks similar to the declaration of a traditionalclass, as
demonstrated by the following code.
[AttributeUsage(AttributeTargets.Method)]public
class MyAttribute : Attribute
{
// . . .
}
This attribute definition demonstrates the following points:
• Attribute classes must be declared as public classes.
• All attribute classes must inherit directly or indirectly from System.Attribute.
• In Microsoft Visual Basic, all custom attribute classes must have
the System.AttributeUsageAttribute attribute.

Declaring Constructors
Attributes are initialized with constructors in the same way as traditional classes. The followingcode
fragment illustrates a typical attribute constructor. This public constructor takes a parameter and
sets a member variable equal to its value.
public MyAttribute(bool myvalue)
{
this.myvalue = myvalue;
}
You can overload the constructor to accommodate different combinations of values. If you also
define a property for your custom attribute class, you can use a combination of named and
positional parameters when initializing the attribute.. Note that in Visual Basic, constructors for an
attribute class should not use a ParamArray argument.

Declaring Properties
If you want to define a named parameter or provide an easy way to return the values stored byyour
attribute, declare a property. Attribute properties should be declared as public entities with a
description of the data type that will be returned. Define the variable that will hold the value of
your property and associate it with the get and set methods. The following code example
demonstrates how to implement a simple property in your attribute.
public bool MyProperty
PGDAC-MS.Net Page 10
{
get {return this.myvalue;}
set {this.myvalue = value;}
}

Custom Attribute Example


This section incorporates the previous information and shows how to design a simple attributethat
documents information about the author of a section of code. The attribute in this example stores
the name and level of the programmer, and whether the code has been
reviewed. It uses three private variables to store the actual values to save. Each variable is
represented by a public property that gets and sets the values. Finally, the constructor is defined
with two required parameters.

What is reflection?
Reflection provides objects (of type Type) that describe assemblies, modules and types. You can use
reflection to dynamically create an instance of a type, bind the type to an existing object, or get the
type from an existing object and invoke its methods or access its fields and properties. If you are
using attributes in your code, reflection enables you to access them.
Uses for Reflection C#
1. Use Module to get all global and non-global methods defined in the module.
2. Use MethodInfo to look at information such as parameters, name, return type, access
modifiers and implementation details.
3. Use EventInfo to find out the event-handler data type, the name, declaring type and
custom attributes.
4. Use ConstructorInfo to get data on the parameters, access modifiers, and implementation
details of a constructor.
5. Use Assembly to load modules listed in the assembly manifest.
6. Use PropertyInfo to get the declaring type, reflected type, data type, name and writable
status of a property or to get and set property values.
Other uses for Reflection include constructing symbol tables, to determine which fields to
persist and through serialization.

File Handling in C#
All the objects created at runtime reside on heap section primary memory. Once they are out of
scope the objects are released by garbage collector. So the data stored in an object cannot be
reused once the program is terminated. Therefore we store the data on secondary storage devices
in the form of file. File handling is an unmanaged resource in your application system. It is outside
your application domain (unmanaged resource). It is not managed by CLR.

What is a stream?
A stream is a sequence of bytes. In the file system, streams contain the data that is written to a file,
and that gives more information about a file than attributes and properties. When you open a file
for reading or writing, it becomes stream. Stream is a sequence of bytes traveling from a source to a
PGDAC-MS.Net Page 11
destination over a communication path. The two basic streams are input and output streams. Input
stream is used to read and output stream is used to write. The System.IO namespace
includes various classes for file handling.
Stream is the abstract base class of all streams. A stream is an abstraction of a sequence of bytes,
such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. The
Stream class and its derived classes provide a generic view of these different types of input and
output, and isolate the programmer from the specific details of the operating system and the
underlying devices.

Streams involve three fundamental operations:


1.You can read from streams. Reading is the transfer of data from a stream into a data structure,
such as an array of bytes.
2.You can write to streams. Writing is the transfer of data from a data structure into a stream.
3.Streams can support seeking. Seeking refers to querying and modifying the current position within
a stream. Seek capability depends on the kind of backing store a stream has. For example, network
streams have no unified concept of a current position, and therefore typically do not support
seeking.
Some of the more commonly used streams that inherit from Stream are FileStream, and
MemoryStream.

What is FileStream class?


Use the FileStream class to read from, write to, open, and close files on a file system, and to
manipulate other file-related operating system handles, including pipes, standard input, and
standard output. You can use the Read, Write, CopyTo, and Flush methods to perform
synchronous operations, or the ReadAsync, WriteAsync, CopyToAsync, and FlushAsync methods
to perform asynchronous operations.

Why there is a need of reader and writer classes?

As shown in the picture above, FileStream is byte oriented. But if we want to read and write
characters then we need character reader and writer streams .

PGDAC-MS.Net Page 12
TextReader is the abstract base class of StreamReader and StringReader, which read characters from
streams and strings, respectively. Use these derived classes to open a text file for reading a
specified range of characters, or to create a reader based on an existing stream.
TextWriter is the abstract base class of StreamWriter and StringWriter, which write characters to
streams and strings, respectively. Create an instance of TextWriter to write an object to a string,
write strings to a file, or to serialize XML.

The BinaryReader class is used to read binary data from a file. A BinaryReader object is createdby
passing a FileStream object to its constructor.
The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created
by passing a FileStream object to its constructor.

What is Serialization?
Serialization is converting object to stream of bytes. It is a process of bringing an object into aform
that it can be written on stream. It's the process of converting the object into a form so that it can be
stored on a file, database or memory. It is transferred across the network. Mainpurpose is to save
the state of the object.

What is deserialization?
Deserialization is converting stream of byte to object. Deserialization is the reverse process of
serialization. It is the process of getting back the serialization object (so that) it can be loaded into
memory. It lives the state of the object by setting properties, fields etc.

What are different types of Serialization techniques?


Different Types of Serialization
The Microsoft .NET Framework provides an almost bewildering variety of ways to serialize an object.
This chapter focuses on XML serialization, but before we get into the details, I'd like to briefly
examine and compare the various serialization methods offered.

XML Serialization
XML serialization allows the public properties and fields of an object to be reduced to an XML
document that describes the publicly visible state of the object. This method serializes only public
properties and fields—private data will not be persisted, so XML serialization does not provide full
fidelity with the original object in all cases. However, because the persistence

PGDAC-MS.Net Page 13
format is XML, the data being saved can be read and manipulated in a variety of ways and on
multiple platforms.

The benefits of XML serialization include the following:


Allows for complete and flexible control over the format and schema of the XML produced by
serialization.Serialized format is both human-readable and machine-readable.

Easy to implement. Does not require any custom serialization-related code in the object to be
serialized.The XML Schema Definition tool (xsd.exe) can generate an XSD Schema from a set of
serializable classes, and generate a set of serializable classes from an XSD Schema, making it easy to
programmatically consume and manipulate nearly any XML data in an object-oriented (rather than
XML-oriented) fashion.

Objects to be serialized do not need to be explicitly configured for serialization, either by the
SerializableAttribute or by implementing the ISerializable interface.
The restrictions of XML serialization include the following:

The class to be serialized must have a default (parameterless) public constructor.

Read-only properties are not persisted.

Only public properties and fields can be serialized.

SOAP Serialization

SOAP serialization is similar to XML serialization in that the objects being serialized are persisted as
XML. The similarity, however, ends there. The classes used for SOAP serialization reside in
theSystem.Runtime.Serialization namespace rather than the System.Xml.Serializationnamespace
used by XML serialization. The run-time serialization classes (which include both the SoapFormatter
and the BinaryFormatter classes) use a completely different mechanism for serialization than the
XmlSerializer class.

The benefits of SOAP serialization include the following:


Produces a fully SOAP-compliant envelope that can be processed by any system or service that
understands SOAP.Supports either objects that implement the ISerializable interface to control their
own serialization, or objects that are marked with the SerializableAttribute attribute
Can deserialize a SOAP envelope into a compatible set of objects.
Can serialize and restore non-public and public members of an object.

The restrictions of SOAP serialization include the following:


The class to be serialized must either be marked with the SerializableAttributeattribute, or must
implement the ISerializable interface and control its own serialization and deserialization.Only
understands SOAP. It cannot work with arbitrary XML schemas.

PGDAC-MS.Net Page 14
Binary Serialization
Binary serialization allows the serialization of an object into a binary stream, and restoration from a
binary stream into an object. This method can be faster than XML serialization, and the binary
representation is usually much more compact than an XML representation. However, this
performance comes at the cost of cross-platform compatibility and human readability.

The benefits of binary serialization include the following:


It's the fastest serialization method because it does not have the overhead of generating an XML
document during the serialization process.The resulting binary data is more compact than an XML
string, so it takes up less storage space and can be transmitted quickly.

Supports either objects that implement the ISerializable interface to control its own serialization, or
objects that are marked with the SerializableAttribute attribute.

Can serialize and restore non-public and public members of an object.

The restrictions of binary serialization include the following:


The class to be serialized must either be marked with the SerializableAttributeattribute, or must
implement the ISerializable interface and control its own serialization and deserialization.
The binary format produced is specific to the .NET Framework and it cannot be easily used from
other systems or platforms.
The binary format is not human-readable, which makes it more difficult to work with if the original
program that produced the data is not available.

What does ActiveX Data Object.NET (ADO.NET) mean?


ActiveX Data Object.NET (ADO.NET) is a software library in the .NET framework consisting of

DotNet ADO.NET
Application (Data Access DB
Mechanism)
software components providing data access services.
ADO.NET is designed to enable developers to write managed code for access to data sources, which
can be relational or non-relational (such as XML or application data). This feature of ADO.NET
Helps to create data-sharing, distributed applications. ADO.NET provides connected access to a
database connection using the .NET-managed providers and disconnected access using datasets,
which are applications using the database connection only during retrieval of data or for data
update. Dataset is the component helping to store the persistent data in memory to provide
disconnected access for using the database resource efficiently and with better scalability.
The architecture of ADO.NET is based on two primary elements:

.NET framework data provider and DataSet


A .NET data provider is a software library consisting of classes that provide data access services such
PGDAC-MS.Net Page 15
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.
A .NET data provider serves as a channel to retrieve and update data existing in the data store
irrespective of data sources. ADO.Net already has given providers that are database specific.

Oracle

ADO.Net has database


specific Providers .Net Application
MSSQL
Server

MySQL

A .NET data provider consists of the following core objects:


• The Connection object is used to connect to a specific data source
• The Command object executes a command against a data source
• DataReader reads data from the data source in read-only, forward-only mode
• DataAdapter populates a data set and resolves an update with the data source
A .NET data provider abstracts the database's interaction with the application and therefore
simplifies application development. However, to achieve the best performance of an application
together with capability and integrity, the right .NET data provider has to be selected based on
factors like design, the data source of the application, application typ (middle or single tier), etc.

DataSet
The huge mainstream of applications built today involves data manipulation in some way -- whether
it be retrieval, storage, change, translation, verification, or transportation. For an application to be
scalable and allow other apps to interact with it, the app will need a common mechanism to pass the
data around. Ideally, the vehicle that transports the data should contain the base data, any related
data, and metadata, and should be able to track changes to the data.Here's where the ADO.NET
There are two ways of Data access mechanisms.
1.Connected Architecture 2.Disconnected Architecture
Connected Architecture

PGDAC-MS.Net Page 16
.Net Provider

Connection

Command
DB
DataReader

Connection Oriented architecture is achieved by the use of Connection, Command and


DataReader object.

The Connection objects define the data provider, database manager instance, database,security
credentials, and other connection-related properties.Important methods of connection object
Open() - Opens a database connection with the property settings specified bythe
ConnectionString.
Close() - Closes the database connection.

The Command object works with the Connection object and used to execute SQL queries or Stored
Procedures against the data source. You can perform insert, update, delete, and select operations
with this object. It requires an instance of a Connection Object for executing the SQL statements as
Steps for executing SQL query with command object
1.Create a Connection Object and initialize with connection string.
2.Create the command object and initialize with SQL query and connection object.
3.Open the connection.
4.Execute query with the help of any one method of command object.
5.Store the result in DataReader object (In case of select SQL query)
6.Close the connection.

PGDAC-MS.Net Page 17
Important method of command object
ExecuteReader: This method works on select SQL query. It returns the DataReader object. UseDataReader
read () method to retrieve the rows.
ExecuteScalar: This method returns single value. Its return type is Object. When you want
single value (First column of first row), then use ExecuteScalar () method. Extra columns or rows
are ignored. ExecuteScalar method gives better performance if SQL statements have aggregate
function.
ExecuteNonQuery: If you are using Insert, Update or Delete SQL statement then use thismethod.
Its return type is Integer (The number of affected records).
ExecuteXMLReader: It returns an instance of XmlReader class. This method is used to returnthe
result set in the form of an XML document.

Important properties of Command class


1.Connection 2.CommandText 3.CommandType 4.CommandTimeout

CommandType is an important property of Command class. This property is used to determinewhich


type of command being executed. It supports the following enumerators.
CommandType.StoredProcedure: It informs the Command object that the stored procedurewill
be used in place of simple SQL statements.
CommandType.Text: It informs the Command object that the CommandText value contains aSQL
query.
CommandType.TableDirect: It indicates that the CommandText property contains the name of a
table.

Using DataReader object


DataReader object works in connected mode. It is read only and forward only object. It is fast
compare to DataSet. DataReader provides the easy way to access the data from database. It can
increase the performance of application because it reads records one by one. Use read() method of
DataReader to access the record.

For initializing the DataReader object, call the ExecuteReader method of the Command object.It
returns an instance of the DataReader.
SqlCommand cmd = new SqlCommand("Your SQL query", conn);
SqlDataReader readerObj = cmd.ExecuteReader();

Once your task completed with the data reader, call Close() method to close the dataReader.
readerObj.Close();

PGDAC-MS.Net Page 18
Important properties of DataReader object
FieldCount: It provides the number of columns in the current row.
HasRows: It provides information that, whether data reader contains row or not.
IsClosed: It indicates that whether data reader is closed or not.
RecordsAffected: Returns the number of affected records.
You can also get the value of particular column of the table by using the data reader object.

Disconnected Architecture
A connected mode of operation in ADO.Net is one in which the connection to the underlyingdatabase is
alive throughout the lifetime of the operation. Meanwhile, a disconnected mode of operation is one in
which ADO.Net retrieves data from the underlying database, stores the data retrieved temporarily in the
memory, and then closes the connection to the database.
The architecture of ADO.net in which data retrieved from database can be accessed even when
connection to database was closed is called as disconnected architecture. Disconnected architecture
of ADO.net was built on classes connection, dataadapter, commandbuilder and dataset and
dataview.
Connection : Connection object is used to establish a connection to database and connectionit self
will not transfer any data.
DataAdapter : DataAdapter is used to transfer the data between database and dataset. It has
commands like select, insert, update and delete. Select command is used to retrieve data
from database and insert, update and delete commands are used to send changes to the datain
dataset to database. It needs a connection to transfer the data.

PGDAC-MS.Net Page 19
CommandBuilder : by default dataadapter contains only the select command and it doesn’tcontain
insert, update and delete commands. To create insert, update and delete commands for the
dataadapter, commandbuilder is used. It is used only to create these commands for the dataadapter
and has no other purpose.
DataSet : Dataset is used to store the data retrieved from database by dataadapter and makeit
available for .net application.
To fill data in to dataset fill() method of dataadapter is used and has the following syntax.
Da.Fill(Ds,”TableName”);
When fill method was called, dataadapter will open a connection to database, executes select
command, stores the data retrieved by select command in to dataset and immediately closes the
connection.
As connection to database was closed, any changes to the data in dataset will not be directly sent to
the database and will be made only in the dataset. To send changes made to data in dataset to the
database, Update() method of the dataadapter is used that has the following syntax.
Da.Update(Ds,”Tablename”);
When Update method was called, dataadapter will again open the connection to database, executes
insert, update and delete commands to send changes in dataset to database and immediately closes
the connection. As connection is opened only when it is required and will be automatically closed
when it was not required, this architecture is called disconnected architecture. A dataset can
contain data in multiple tables.

PGDAC-MS.Net Page 20
Difference between Connected and Disconnected Architecture

What is LINQ?
LINQ is an acronym for Language Integrated Query, which is descriptive for where it’s used and what
it does. The Language Integrated part means that LINQ is part of programming language syntax. In
particular, both C# and VB are languages that ship with .NET and have LINQ capabilities. Another
PGDAC-MS.Net Page 21
programming language that supports LINQ is Delphi Prism. The other part of the definition, Query,
explains what LINQ does; LINQ is used for querying data. Notice that I used the generic term “data”
and didn’t indicate what type of data. That’s because LINQ can be used to query many different
types of data, including relational, XML, and even objects.
Another way to describe LINQ is that it is programming language syntax that is used to query

data.
LINQ queries return results as objects. It enables you to uses object-oriented approach on the

result set and not to worry about transforming different formats of results into objects

We Already have ADO.NET, so Why Another Data Access Technology?


Most applications work with data in one form or another, meaning that data is very important to
the work we do as software engineers. It’s so important that the tools we use are constantly
evolving, with the next generation building and improving upon the previous. This doesn’t change
with LINQ, which is the next giant leap in data development technology beyond ADO.NET.

ADO.NET is an object-oriented library, yet we must still reason about data from a relational
perspective. In simple scenarios, we can bind ADO.
Note: The operative term in the previous paragraph is “reduce”. LINQ does not eliminate
Impedance Mismatch, because you must still reason about your data store format. However,LINQ
does remove a lot of the plumbing work you have to do to re-shape your data as an object.

More about Data Source


LINQ is intended to make it easy to query data sources. One of the more popular uses of LINQ isto query
relational databases. However, as you see here, LINQ can query objects. That’s not all, the .NET Framework
includes libraries that allow anyone to create a LINQ provider that can query any data source. Out of the
box, Microsoft ships LINQ to Objects, LINQ to XML, LINQ to SQL (SQL Server), and LINQ to Entities (Entity
Framework). There are also 3rd party LINQ providers that make it easy to query specialized data sources

In the query, we select elements from an array in descending order (high to low). We filter out
elements <= 2. In the loop, we evaluate the expression and print the results.Var

PGDAC-MS.Net Page 22
.NET INTERVIEW QUESTIONS
: C# is a simple, modern and a general-purpose Object-oriented programming language
developed by Microsoft within its .NET framework. Beginner’s Level
Q1. List down the differences between Public, Static and void keywords?
Keyword Description
Public It is an access specifier which states that the method of a class can be accessed
publicly
Static It is a keyword used for declaring a member of a type, specific to that type
void It states that the method does not return any value

Q2. Define C# and list the features.


Ans- C# is an object-oriented, typed safe and manage language that is compiled by .NET
framework and was developed by Microsoft back in 2000. The idea was that it will be used
in the development of all kinds of software aiming at different platforms like Windows,
Web, mobile using only one programming language. Fast forward to the present day it is
one of the most popular programming languages worldwide, millions of developers use this
language to build all kinds of software. Some of the features of C#(sharp) are: • Use of
Constructors and Destructors • Easy to grasp • General Purpose and Object-Oriented •
Structured language • Platform independent for compilation

Q3. List down the reason behind the usage of C# language.


1.Easy to pickup 2.Component oriented language 3.Follows a Structured approach
4.Produces readable and efficient programmes 5.Once written can be compiled on different
platforms 6.Passing parameters is easy

Q4. What are the advantages of using C#?


1.Easy to learn 2.Object-Oriented language 3.The syntax is easy to grasp 4.Component
oriented 5.Part of the .NET framework
Q5. What are the different types of comments in C#?
a. Single line comments
// hello, this is a single line comment
b. Multiline comments
/* Hello this is a multiline comment
last line of comment*/
c. XML comments
/// Hello this is XML comment

Q6. Illustrate the process of code compilation in C#?


Ans- There exist four steps in the process of code compilation: a. Compilation of Source
code in managed code b. Clubbing the newly created code into assembly c. Loading the CLR
(Common Language Runtime) d. Execution of assembly through CLR

Q7. List down the access modifiers available in C#. Ans- Following are the access modifiers
• Public- When an attribute or method is defined as public it can be accessed from any part
of code.
PGDAC-MS.Net Page 23
• Private- A private attribute or method can be accessed from within the class itself. •
Protected- When a user defines a method or attribute as protected then it can be accessed
only within that class and the one inheriting the class.
• Internal- When an attribute or method is defined as internal then it will be accessed from
that class at the current assembly position.
• Protected Internal- When you define an attribute or method as protected internal, then
it’s access restricted to classes within the current project assembly or different types
defined by that class.

Q8. List down the different IDE’s Provided by Microsoft for C# Development.
1.Visual Studio Express (VCE) 2.Visual Studio (VS) 3.Visual Web Developer 4.MonoDevelop
5.browxy

Q9. Distinguish between Continue and Break Statement?


Ans- Using break statement you can ‘jump out’ of the loop whereas while making use of
continue statement you can jump over an iteration and continue the loop execution.

Q10. What are the different approaches of passing parameters to a method?


Ans- There are three ways of passing parameters to a method:
Value Parameters- Under this method the actual value of an argument is copied to the
formal parameter of the function. In, this case the changes made into the formal parameter
of the function have no effect on the actual value of the argument.
Reference Parameters- This method copies the argument referring to the memory location
into the formal parameter. Meaning changes made to the parameter affect the argument.
Output Parameters- This method returns more than one value.
Intermediate level C# Interview Questions
Q11. Distinguish between finally and finalize blocks?
Ans- finally block is called after the execution of try and catch blocks, It is used for exception
handling whether or not the exception has been caught this block of code gets executed.
Generally, this block of code has a cleaner code.
The finalize method is called just before the garbage collection. Main priorities are to
perform clean up operation for unmanaged code, it is automatically invoked when an
instance is not subsequently called.

Q12. What is Managed or Unmanaged Code?


Ans- Managed code is one which is executed by CLR (Common Language Runtime) in simple
terms it means all the application code is dependent on the .NET platform, considered as
overseen in view of them. Unmanaged code is any code that is executed by runtime
application of some other structure different from .NET platform. The runtime of application
will deal with memory, security and other execution activities.
Q13. What is an Object?
Ans- Object is an instance of a class, It is used for accessing the methods of a class. “New”
keyword is used for the creation of an object, a class that creates an object in the memory
location contains the information about methods, variables, and behavior of that class.

Q14. What is a Class?


Ans- A class is a blueprint of an object. It defines different kinds of data and functionalities
PGDAC-MS.Net
objects will have. A class enables you to create your own custom types by clubbing together Page 24
variables of different types, methods, and events. In C# a class is defined by a class keyword.
Q15. Define an abstract class?
Ans- It is a type of class whose objects can’t be instantiated, It contains something like a
single approach or technique and indicated by the keyword ‘abstract’.

Q16. Define sealed classes in C#?


Ans- You create sealed classes in situations when you want to restrict the class to be
inherited. For doing this sealed modifiers are used. If you forcefully specify a sealed class as
a base class then a compilation error occurs.

Q17. Define a Partial class?


Ans- A partial class is the only one that essentially splits the definition of a class into multiple
classes in either same source code files or multiple source code files. One can create a class
definition in multiple files but that is compiled as one class at run-time and when an
instance of this class is created, one can access all methods from every source file with the
same object. It is indicated by the keyword ‘partial’.

Q18. List down the fundamental OOP concepts?


• Inheritance- Ever heard of this dialogue from relatives “you look exactly like your
father/mother” the reason behind this is called ‘inheritance’. From the Programming aspect,
It generally means “inheriting or transfer of characteristics from parent to child class
without any modification”. The new class is called the derived/child class and the one from
which it is derived is called a parent/base class.
• Polymorphism- You all must have used GPS for navigating the route, Isn’t it amazing how
many different routes you come across for the same destination depending on the traffic,
from a programming point of view this is called ‘polymorphism’. It is one such OOP
methodology where one task can be performed in several different ways. To put it in simple
words, it is a property of an object which allows it to take multiple forms.
• Encapsulation- In a raw form, encapsulation basically means binding up of data in a single
class.A class shouldn’t be directly accessed but be prefixed in an underscore.
• Abstraction- Suppose you booked a movie ticket from bookmyshow using net banking or
any other process. You don’t know the procedure of how the pin is generated or how the
verification is done. This is called ‘abstraction’ from the programming aspect, it basically
means you only show the implementation details of a particular process and hide the details
from the user. It is used to simplify complex problems by modeling classes appropriate to
the problem.An abstract class cannot be instantiated which simply means you cannot create
objects for this type of class. It can only be used for inheriting the functionalities.
Q19. Explain the process of inheriting a class into another class?
Ans- Colon is used as an inheritance operator in C#. Place the colon and the class name.
public class Derivedclass: childclass

Q20. Define method overloading in C#?


Ans- Method overloading essentially is creating multiple methods with the same name and
unique signatures with the same class. When you compile, the compiler makes use of
overload resolution to determine the specific method which will be invoked.
PGDAC-MS.Net Page 25
Q21. List the differences between method overriding and method overloading?
Ans- Under Method overriding the definition of the derived class is changed which in turn
changes the method behavior. Method overloading is simply creating a method with the
same name under the same class under different signatures.

Q22. Explain StreamReader/StreamWriter class?


Ans- Streamreader and StreamWriter are classes of namespace.System.IO. Used when we
want to read or write charact90, Reader based data, respectively.
members of StreamReader are: close(), Read(), Readline(). members of Streamwriter are:
close(), write(), writeline().

Q23. What is an Interface?


Ans- An Interface is basically a class with no implementation. It contains only the
declaration of properties, attributes, and events.

Q24. Distinguish between a class and struct?


class Struct
It supports inheritance It does not support inheritance
It is Pass by reference It is pass by value
Members are private by default Members are public by default
Considered good for larger complex objects Considered good for small models

Q25. List the difference between the Virtual method and the Abstract method?
Ans- A Virtual method must always have a default implementation. However, it can be
overridden in a derived class by the keyword override.
An Abstract method doesn’t have any implementation. It resides in the abstract class, and
also it is mandatory that the derived class must implement abstract class. Use of override
keyword is not necessary.
Q26. Illustrate Namespaces in C#?
Ans- Namespaces are used for organizing large code projects. “System” is one of the most
popular and widely used namespaces in C#. One can create their own namespace and use
one into another called nesting.
Q27. Define using statement in C#?
Ans- “Using” keyword simply denotes that the particular namespace is being used by the
program. For ex- using System, Here System is a namespace. The class console is defined
under system, so we can use the Console.Writeline(…) or Readline in our program.

Q28. Define an Escape Sequence, Name few strings in Escape Sequence?


Ans- An Escape Sequence is denoted by a backslash (). The backslash merely indicates that
the character it is following should be interpreted literally or is a special character. An
escape sequence is a single character.
Few escape sequences are as follows:
n – newline character, b – backspace ,– backlash, ‘ – Single quote, ” – Double quote

Q29. Define Boxing and Unboxing in C#?


Ans- Converting a value type to the reference type is called boxing.
PGDAC-MS.Net
Example: int value = 10 Page 26
//-------Boxing--------//
object boxedvalue = value1;
Explicit conversion of the same reference type i.e. converting it back to the value type is
called Unboxing.
Example: 1//----------------Unboxing-------// int UnBoxing = int(boxedvalue);
To know more about Boxing and Unboxing in Java you can go refer this article- Boxing in
Java.

Q30. Define an array?


Ans- An array is used to store multiple variables of the same type. Collection of variables
stored in a contiguous memory location.
Example: double numbers = new double[10];
int[] Score = new int[4] {25,24,23,22,21,20}
Above given example above is of a Single Dimensional array. It is a linear array where values
are stored in a single row. A multidimensional array is the one having more than one
dimension. A good example would be of a rectangle.
Example:
int[,] numbers = new int[4,3]{ {1,2} {2,3} {3,4} {4,5} };

Q31. Define a Jagged Array in C#?


Ans- A Jagged array is referred to as an “array of arrays”. It is an array whose elements are
arrays, the element of the same can be of different dimensions and sizes. The length of each
array index can differ. Example: int[][] jagArray = new int[5][];

Q32. Distinguish between Array and Arraylist in C#?


Array ArrayList
Array uses the vector array for storing the ArrayList uses the LinkedList to store the
elements elements
Size of the Array must be defined until There’s no need for specifying storage size.
redim used(vb)
An array is a specific data type storage ArrayList can store everything as an object
Typecasting is not necessary Typecasting is necessary
There is no RunTime exception There is a RunTime error exception
Elements can’t be inserted or deleted in Elements can be inserted or deleted in
between between

Q33. Define Collections?


Ans- A collection essentially works like a container for instances of other classes. Every class
implements Collection Interface

Q34. Write a short note on Interface?


Ans- An Interface is a class with no implementation. It consists of a declaration of methods,
Parameters, and values.
Advance Level
Q35. Illustrate Serialization?
Ans- A process that involves converting some code into its binary format is known as a
PGDAC-MS.Net Page 27
serialization in C#. In doing so it gives the flexibility where code can be stored easily and or
written to a disk or some other storage device. Serialization is used when there is a strict
need for not losing the original code.
Serialization in C# is of three types:
Binary Serialization- It is fast and demands less space, converts any code into its binary
format. Serialize and restore public and non-public properties.
SOAP- Generates a complete SOAP compliant envelope used by any system by its ability to
understand SOAP. Classes under this type of Serialization reside in
System.Runtime.Serialization.
XML Serialization- It serializes all the public properties to XML document. Readability being
one factor, an XML document can also be manipulated in various ways. Classes under this
type reside in System.sml.Serialization.

Q36. Define Parsing? Explain how to Parse a DateTime String?


Ans- Parsing is a method of converting a string into another data type.
string text = "200";
int num = int.Parse(text);
In the above-given example, 200 is an integer. So, the Parse method converts the
string 200 into its own base type, i.e. int. To parse a DateTime String let’s see a small
Example: string dateTime = "Aug 26,2019"; Datetime parsedvalue =
Datetime.Parse(dateTime);

Q37. Define Delegate?


Ans- Delegate is a variable that holds the reference to a method. It is a function pointer of
the reference type. All Delegates are derived from the System.Delegate namespace. Both
Delegate and the method that it refers to can have the same signature. Let’s see a small
example.

Q38. Distinguish between System.String and System.Text.StringBuilder classes?


Ans – System.String is immutable. Whenever you modify the value of a string variable then
a new memory is allocated to the new value and previous memory allocation is released.
System.Text.StringBuilder is mutable i.e. supports the fact that a variety of operations can
be performed without allocating a seperate memory location for the already modified
string.

Q39. Illustrate the differences between the System.Array.CopyTo() and


System.Array.Clone()?
Ans – Using the Clone() method, a new array object is created containing all elements of the
original array. Using the CopyTo() method all the elements of the existing array gets copied
into another existing array. Both use a shallow copy method.

Q40. Write the Syntax for catching an exception in C#?


Ans – To catch an Exception we make use of try-catch blocks. The catch block has a
parameter of the system.Exception type.
try
{
GetAllData();
PGDAC-MS.Net
} Page 28
catch(Exception ex){
}

Q41. Explain about generics in C#.NET?


Ans- Generics are used to make reusable code classes which decrease the code redundancy,
• Increase type safety, performance, and optimization
• Using Generics one can do a variety of things like create collections
• To create Generic collection, System.namespace
• The generic namespace should be used inspite of classes such as ArrayList in the System
• Generics instigates the usage of a parameterized type

Q42. List down the differences between “dispose” and “finalize” methods in C#.
Ans- Dispose() is called when we want an object to release unmanaged resources with
them. Whereas, Finalize() is used for the same purpose but it doesn’t assure garbage
collection of an object.

Q43. Define C# I/O classes? List the commonly used classes?


Ans- C# consists of System.IO namespace which has classes that compute and perform
various operations on files like creating, deleting, opening and closing etc.
Few commonly used I/O classes are listed below:
File- Helps in manipulating file.
StreamWriter- Generally used for writting characters to a stream.
StreamReader- Generally used for reading characters to a stream.
StringWriter- Used for writing a string buffer.
Stringreader- Used for reading a string buffer.

Q44. Define thread? Explain about Multithreading?


Ans- Thread is a set of instructions that when executed enables the program to perform
concurrent processing. Concurrent processing helps in doing more than one process at a
time. By default, C# consists of only thread. Other threads can be created to execute the
code in parallel with original thread.
Thread follows a life cycle where it starts whenever a thread is created and gets
terminated immediately after the execution. The namespace it follows is System.Threading
which has to be included to create threads and use its members.
Threads are created by extending the thread class. Start() method marks the
beginning of the thread execution.
//callThread is our target method//
ThreadStart methodThread = new ThreadStart(CallThread);
Thread childThread = new Thread(methodThread);
childThread.start();
C# can also execute more than proceeses/task at a time which is done by handling
different processes at different time labeled as “multithreading”. Several operations of the
same are listed below: • Start • Sleep • Abort • Suspend • Resume • Join

Q45. What are Events?


Ans- Events in C# follow a concept where it consists of a Publisher, Subscriber, Notification
PGDAC-MS.Net
and a handler. You can think of an event as nothing but an encapsulated delegate. Page 29
public Delegate void TestEvent();
public TestEvent TestEvent1;

Q46. Explain Synchronous and Asynchronous Operations?


Ans- Synchronization is a way of creating a thread-safe code where only a single thread will
access the code in a given time. A synchronous call waits for completion of method and then
continous the program flow. Synchronous programming adversely affects the UI operations
that normally happens when user tries to perform time-consuming operations since only
one thread is used.
In Asynchronous operation, the method call immediately returns allowing the program to
perform other operations while the method called completes its share of work in certain
circumstances.

Q47. Explain Async and Await?


Ans- Async and Await keywords are mostly used for creating asynchronous methods in C#.
Usage of the same is shown through an example:
public async Task>CalculateCount()
{
await Task.Delay(2000);
return 1;
}
public async task mytestmethod()
{
Task> count = CalculateCount();
int result = await count;
}
In the above-given code async keyword is used for method declaration. The Count is of a
task type int which calls the method CalculateCount(). CalculateCount() starts execution and
calculates something.

Q48. Explain Deadlock?


Ans- A deadlock is a situation that arises when a process isn’t able to complete it’s execution
because two or more than two processes are waiting for each other to finish. This usually
occurs in multi-threading. In this, a shared resource is being held up by a process and
another process is waiting for the first process to get over or release it, and the thread
holding the locked item is waiting for another process to complete.

Q49. Illustrate Race Condition?


Ans- A Race Condition occurs in a situation when two threads access the same resource and
try to change it at the same time. The thread which accesses the resource first cannot be
predicted. Let me take a small example where two threads X1 and X2 are trying to access
the same shared resource called T. And if both threads try to write the value to T, then the
last value written to T will be saved.

Q50. What is Thread Pooling?


Ans- A Thread pool is a collection of threads that perform tasks without disturbing the
PGDAC-MS.Net
primary thread. Once the task is completed by a thread it returns to the primary thread. Page 30

You might also like