Download as pdf or txt
Download as pdf or txt
You are on page 1of 168

What is .net framework?

.net framework is a complete environment that allows developers to develop, run


and deploy following applications.

o Console Application
o Windows Forms applications
o Windows Presentation Foundation (WPF) application
o Web applications (ASP.net applications)
o Web Services
o Windows Services
o Service oriented applications using Windows Communication Foundation(WCF)
o Workflow-enabled applications using Windows Workflow Foundation (WF)

What are the main components of .net framework?

(The above Image is referred from slideshare)

The following are the key components of .net Framework.


o Class Library

.net framework contains a rich collection of classes that are readily available
for the developers such as working with files,data storage,input output
etc..The classes in Framework Class Library(FCL) are logically grouped under
various namespaces.

o Common Language Runtime


o Facilitates the interoperability between different .net languages such as
C#,visual basic etc
o When you run a .net application, the language compiler first compiles
the source code into intermediate code called Microsoft Intermediate
Language (MSIL) code.
o THE MSIL code is used by Just-In-Time(JIT) compiler to convert into the
native machine code, which is final executable code
o CLR also manages the allocation and deallocation of system resources
o Dynamic Language Runtime
o DLR is a runtime environment that adds a set of services for dynamic
languages to the CLR
o DLR makes it easier to develop dynamic languages to run on .net
framework and give them .net interoperability
o DLR introduces dynamic objects in C#
o DLR helps you create libraries that support dynamic operations
o Examples of languages developed by using DLR is IronPython,IronRuby etc
o Application Domains

Provides isolation between applications.

o Runtime Host
o Load the runtime environment into execution process of a .net
application
o Create an application domain in .net process
o Common Type System

Maintains data integrity across the code written in different .net compliant
programming languages.

o Meta Data and self describing components

.net framework uses MetaData of a code or an assembly to exchange


information with other code

o Cross-languate Interoperability

This explains how managed objects created in different programming


language can interact with one another

o .net framework Security


Specifies that .net framework consists of technologies and tools that can be
used by developers to protect the resources and code from unauthorized
user.

o Profiling

Enables you to use the profilers dynamically with the running process.After a
profiler performs all requested profiling tasks you can detach it.

o side by side execution

Enables an application to work with multiple versions of CLR simultaneously

What is the difference between System.String and


System.StringBuilder classes?
String and StringBuilder classes are used to store string values but there are few
differences.
String is immutable(readonly) because a value once assigned to a string object can
not be changed after its creation. When the value in STring object is modified, a
new object is created in memory with a new value assigned to it.But, the
STringBuilder class is mutable as it occupies the same space after you change the
value.The StringBuilder class is more efficient where you have to perform a large
amount of string manipulation.

Explain the role of CLR in .net framework


CLR provides an environment to execute .net applications on target machines.

o Automatic Memory Management

CLR invokes multiple built in functions of .net framework to allocate and


deallocate memory of .net objects.

o Garbage Collection

Prevents memory leaks during program execution

o Code Access Security

Imposes security and restrictions during execution of programs

o Code Verification
Specifies that CLR enforces type safety and prevents a source code from
performing illegal operations

o JIT Compilation of .net code

Loads MSIL code on target machine for execution.

What is JIT compiler in .net framework?


o Loads MSIL in target machine for execution
o Translates the MSIL code of an assembly and uses the CPU architecture of the
target machine to execute .net application
o Stores the resulting native code so that it will be available for subsequent
calls
o Enforces type-safety in runtime environment of .net framework

What is Microsoft Intermediate Language (MSIL)?


Each .net compiler produces an intermediate code after compiling the source code.
The intermediate code is common for all languages and is understandable to .net
environment. This intermediate code is known as MSIL.

What is Common Language specification (CLS)?


o CLS enables interoperability between .net compliant language
o CLAs is a subset of CTS

What is Common Type System (CTS)?


It contains a type system that is common across all languages.Two CTS-Compliant
languages don’t require type conversion when calling the code written in another
language. CTS provides base set of data type for all languages. However, the
language uses aliases for the base data types provided by CTS.

What is the difference between managed and


unmanaged code?
Managed code is the code that is executed directly by the CLR instead of operating
system.The code compiler first complies the managed code to Intermediate
Language (IL).This code does not depend on machine configurations and can be
executed in different machines.
Unmanaged code is the code that is executed by the operating system outside the
CLR environment.It is dirctly compiled to machine code which depends on machine
configuration.
In managed code, CLR provides different services like Garbage collection, type
safety and security. But in unmanaged code, it is required to be taken care by
developer.

What is the difference between Dispose() and


Finalize() ?

What is Lazy Initialization?


Lazy Initialization is a process by which an object is not initialized until it is first
called in your code.Syste.Lazy<T> supports executing Lazy initialization in your
applications.It helps you to reduce the wastage of resources and memory
requirements to improve performance.

What is side-by-side execution?


side-by-side execution enables you to run multiple versions of an application or
component and CLR on the same machine and same time. As versioning is applicable
only to shared assemblies and not private assemblies, two applications, one using
private assemblies and other using shared assemblies can not be stated as side-by-
side execution.
What are tuples?
Tuples are the fixed size collection that can have elements of either same or
different data types.A user has to define the size of a tuple at the time of
declaration. Tuples are allowed to hold 1 to 8 elements and if there are more than 8
elements,then the 8th element can be defined as anoth tuple. It can be specified as
parameter or return type of a method.

How can you instantiate a tuple?


There are 2 ways to instantiate Tuple.
1. Using the new operator

1 Tuple<String, int> t = new Tuple<String, int>

2 ("Hello",2);

2.Using the create factory method available in Tuple class.

1 Tuple<int,int,int> t = Tuple.Create<int,int,int>(2,4,5);

What is code access security (CAS)?


Code Access Security (CAS) is part of the .net security model that prevents
unauthorized access of resources and operations and restrict the code to perform
particular tasks.

How does CAS works?


There are 2 key concepts of CAS security policy.
1. Code groups
2. Permission
A code group contains assemblies in it in a manner that each .net assembly is related
to a perticular code group and some permissions are granted to each code group.
Assembly execution involves following steps.

o Evidences are gathered about assemblies


o The assembly is assigned to a code group depending on evidences
o Security rights are allocated to the assembly
o Assembly runs as per the rights assigned to it

How can you turn on and turn off CAS?


You can use the Code Access Security Tool (Caspol.exe) to turn security on or off.
The commands are:
– caspol -security off (turn off security)
– caspol -security on(turn onsecurity)

What is the execution process for managed code?


o Choosing a language compiler
o Compiling the code to MSIL
o Compiling MSIL to native code
o Executing the Code

What are code contracts?


Code contracts help you to express the code assumptions and statements stating the
behavior of your code in language neutral way. The contracts are included in form of
pre-conditions, post-conditions and object-invariants. The contracts help you to
improve testing by enabling run-time checking, static contract verification and
document generation.

What is memory-mapped files?


Memory-mapped files allow you to map the content of a file to the logical address of
an application.These files enable the multiple processes running on the same
machine to share data with each other.
1. What is Garbage Collection?

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 program manipulates the object, and at some point the object may no longer be
needed.
When the object is no longer accessible to the program and becomes a candidate for
garbage collection.

There are two places in memory where the CLR stores items while your code
executes.

stack
heap
The stack keeps track of what’s executing in your code (like your local variables),
and the heap keeps track of your objects.

Value types can be stored on both the stack and the heap.

For an object on the heap, there is always a reference on the stack that points to it.

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.

In unmanaged environments without a garbage collector, you have to keep track of


which objects were allocated on the heap and you need to free them explicitly. In
the .NET Framework, this is done by the garbage collector.

2. What are strong references and weak references


in GC?
The garbage collector cannot collect an object in use by an application while the
application’s code can reach that object. The application is said to have a strong
reference to the object.

A weak reference permits the garbage collector to collect the object while still
allowing the application to access the object. A weak reference is valid only during
the indeterminate amount of time until the object is collected when no strong
references exist. When you use a weak reference, the application can still obtain a
strong reference to the object, which prevents it from being collected. However,
there is always the risk that the garbage collector will get to the object first before
a strong reference is re-established.

Weak references are useful for objects that use a lot of memory, but can be
recreated easily if they are reclaimed by garbage collection.

3. How GC come to know that object is ready to get


collected?
GC normally collects objects when the object is not reachable i.e. not in reference.
The garbage collector uses the following information to determine whether objects
are live:

Stack roots. Stack variables provided by the just-in-time (JIT) compiler and stack
walker.
Garbage collection handles. Handles that point to managed objects and that can be
allocated by user code or by the common language runtime.
Static data. Static objects in application domains that could be referencing other
objects. Each application domain keeps track of its static objects.

4. What are generations in GC?


After the garbage collector is initialized by the CLR, it allocates a segment of
memory to store and manage objects.

This memory is called the managed heap, as opposed to a native heap in the
operating system.

There is a managed heap for each managed process. All threads in the process
allocate memory for objects on the same heap.

The heap is organized into generations so it can handle long-lived and short-lived
objects. Garbage collection primarily occurs with the reclamation of short-lived
objects that typically occupy only a small part of the heap. There are three
generations of objects on the heap:

Generation 0. This is the youngest generation and contains short-lived objects. An


example of a short-lived object is a temporary variable. Garbage collection occurs
most frequently in this generation.

Newly allocated objects form a new generation of objects and are implicitly
generation 0 collections, unless they are large objects, in which case they go on the
large object heap in a generation 2 collection.

Most objects are reclaimed for garbage collection in generation 0 and do not survive
to the next generation.
Generation 1. This generation contains short-lived objects and serves as a buffer
between short-lived objects and long-lived objects.
Generation 2. This generation contains long-lived objects. An example of a long-
lived object is an object in a server application that contains static data that is live
for the duration of the process.

Garbage collections occur on specific generations as conditions warrant. Collecting a


generation means collecting objects in that generation and all its younger
generations. A generation 2 garbage collection is also known as a full garbage
collection, because it reclaims all objects in all generations (that is, all objects in
the managed heap).

Generation 0 – Short-lived Objects


Generation 1- As a buffer between short lived and long lived objects
Generation 2 – Long lived objects

5. 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 pop method when application is done with its use.

Reference types get stored on heap so gets collected by garbage collector.

6. Dispose v/s Finalize

7. Can we pin objects for later references?


The CLR allows us to “pin” an object so that it is not moved during garbage
collection. This can potentially have some big consequences for garbage collection,
though; the heap is still fragmented if an object is pinned during a pass. What’s
more is that if the object becomes eligible for compaction after the pass, it’s still
considered a gen-0 object even though it should have moved to gen-1. C# enables us
to pin an object via the fixed statement.

The fixed statement prevents the garbage collector from relocating a movable
variable. The fixed statement is only permitted in an unsafe context.

8. Does GC work similar for Web Application and


windows application? Is there any difference?
GC works in “Workstation Mode” for windows application , which can be can be
concurrent or non-concurrent. Concurrent garbage collection enables managed
threads to continue operations during a garbage collection.

Starting with the .NET Framework 4, background garbage collection replaces


concurrent garbage collection.

And For Web application it works in “Server garbage collection” mode, which is
intended for server applications that need high throughput and scalability. Server
garbage collection can be non-concurrent or background.

9. How to Force Garbage Collection?


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

Example

1 StreamWriter stream = File.CreateText(“temp.dat”);

2 stream.Write(“some test data”);

3 GC.Collect();

4 GC.WaitForPendingFinalizers();

5 File.Delete(“temp.dat”);

10. Why does Garbage Collection only sweep the


heap?
The garbage collector does scan the stack — to see what things in the heap are
currently being used (pointed to) by things on the stack.

It makes no sense for the garbage collector to consider collecting stack memory
because the stack is not managed that way: Everything on the stack is considered to
be “in use.” And memory used by the stack is automatically reclaimed when you
return from method calls. Memory management of stack space is so simple, cheap
and easy that you wouldn’t want garbage collection to be involved.
1. What is REST?
Representational state transfer(REST) is an abstraction of architecture of world wide
web. REST is an architectural style to design networked application.REST makes
communication between remote computers easy by using the simple HTTP protocol
which support for CRUD (Create, Read, Update, and Delete) operations on the
server.

2. Name some of the commonly used HTTP methods


used in REST based architecture?
Below are the commonly used HTTP methods used in REST.

o GET − Provides a read only access to a resource.


o PUT − Used to update an existing resource.
o DELETE − Ued to remove a resource.
o POST − Used to create a new resource.
o OPTIONS − Used to get the supported operations on a resource.

3. What is a Resource in REST?


o The service has a base URI that represents whole set of resources

ex: CsharpStar.com/posts

o The base uri can be qualified with an identifier specifying an individual


resource

ex: CsharpStar.com/posts/1053

o RESTful services are hierarchical, resources offered by one service can


contain more service
o REST uses various representations to represent a resource where text, JSON,
XML. XML and JSON are the most popular representations of resources

4. Explain REST design principles


There are 5 design principles on REST.

You can read more on this here.

5. Explain different REST Architectural Goals


You can read detailed explanation on each goal here.

6. Which protocol is used by RESTful webservices ?


RESTful web services make use of HTTP protocol as a medium of communication
between client and server.

7. What is messaging in RESTful webservices?


A client sends a message in form of a HTTP Request and server responds in form of a
HTTP Response. This technique is termed as Messaging. These messages contain
message data and metadata i.e. information about message itself.

8. What are the core components of a HTTP Request


and HTTP Response?
There are 5 major components for HTTP Request.
Verb − Indicate HTTP methods such as GET, POST, DELETE, PUT etc.
URI − Uniform Resource Identifier (URI) to identify the resource on server.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Request Header − Contains metadata for the HTTP Request message as key-value
pairs. For example, client ( or browser) type, format supported by client, format of
message body, cache settings etc.
Request Body − Message content or Resource representation.

There are 4 major components for HTTP Response.


Status/Response Code − Indicate Server status for the requested resource. For
example 404 means resource not found and 200 means response is ok.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Response Header − Contains metadata for the HTTP Response message as key-value
pairs. For example, content length, content type, response date, server type etc.
Response Body − Response message content or Resource representation.

9. What is addressing in RESTful webservices?


Addressing refers to locating a resource or multiple resources lying on the server. It
is analogous to locate a postal address of a person.

10. What is URI?


URI stands for Uniform Resource Identifier. Each resource in REST architecture is
identified by its URI.

o Operations on the base URI affect the set of resources as a whole

1. GET lists them


2. POST adds a new resource to the set
3. DELETE deletes the whole set
4. PUT replaces the set with a new set

o Operations on an ID-qualified URI affect an individual resource

1. GET retrieves it
2. DELETE destroys it
3. PUT replaces it or create if doesnot exists

11. What is the purpose of HTTP Verb in REST based


webservices?
VERB identifies the operation to be performed on the resource.
12. What is statelessness in RESTful Webservices?
The communication between client and server must be stateless. This means that
each request from a service consumer should contain all the necessary information
for the service to understand the meaning of the request, and all session state data
should then be returned to the service consumer at the end of each request

13. What are the advantages and disadvantages of


statelessness in RESTful Webservices?
Advantages:
o Web services can treat each method request independently.
o Web services need not to maintain client’s previous interactions. It simplifies
application design.
o As HTTP is itself a statelessness protocol, RESTful Web services work
seamlessly with HTTP protocol
Disadvantages:
o Web services need to get extra information in each request and then
interpret to get the client’s state in case client interactions are to be taken
care of.

14. What is the difference between PUT and POST


operations?
PUT − Used to update an existing resource and POST − Used to create a new
resource.

15. What should be the purpose of OPTIONS and


HEAD method of RESTful web services?
OPTIONS : list down the supported operations in a web service and should be read
only.
HEAD : return only HTTP Header, no Body and should be read only.

16. Explain different statemanagement principles in


REST service?
You can read more on state management here.

17. What is caching?


Caching refers to storing server response in client itself so that a client needs not to
make server request for same resource again and again. A server response should
have information about how a caching is to be done so that a client caches response
for a period of time or never caches the server response.

18. What is the purpose of HTTP Status Code?


HTTP Status code are standard codes and refers to predefined status of task done at
server.

HTTP Status Code:

200 – OK, shows success.


201 – CREATED, when a resource is successful created using POST or PUT request.
Return link to newly created resource using location header.
204 – NO CONTENT, when response body is empty
304 – NOT MODIFIED, used to reduce network bandwidth usage in case of conditional
GET requests
400 – BAD REQUEST, states that invalid input is provided
401 – FORBIDDEN, states that user is not having access to method being used
404 – NOT FOUND, states that method is not available
409 – CONFLICT, states conflict situation while executing the method
500 – INTERNAL SERVER ERROR, states that server has thrown some exception while
executing the method

19. Explain the REST Constraints

You can read more on REST Constraints here.

20. Difference between SOAP and REST services


o REST is simpler to program than SOAP
o Retrieval consists of a URL(GET)
o Creation consists of a URL(POST)
o Update and Delete also simple (PUT,DELETE)
o SOAP semantics are opaque, so it bypasses the features of layered internet
o REST is lightweight on the client side
o you need to write a little bit of script codeand you are off and running
o Javascript frameworks make it browser independent and easy to
integrate
o REST is lightweight in server side
o you need to write a little bit of script codeand you are off and running
o Frameworks support the web servers
What is an exception?
o A .NET exception is an object that describes a runtime error condition.
o When a runtime error condition arises, an object is created that
represents the runtime error and is thrown in the method that has caused the
error.
o That method may handle the exception itself or pass it on. Whatever may be
the way, the exception is caught and processed at some point.
o Exceptions can be generated by the CLR or can be generated by the code.
o Exceptions thrown by .NET are related with primary errors that violate
the rules of the C# language or the constraints of the .NET
execution environment
o .NET exception handling is done with try, catch, throw and finally.
o A try block contains program statements that are required to be monitored

Explain exception handling mechanism in C#?


Exceptions in C# are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for exception
are kept in this block.
catch block : This block catches the exceptions occurred in the try block.
finally block : This block is always executed whether exception is occurred in the try
block or not and occurred exception is caught in the catch block or not.

Explain the difference between error and exception


in C# ?
Exception handling is a mechanism to detect and handle error at run time where as
Errors are occured at development/compile time.

Explain the hierarchy of exceptions in C#?


What is the main use of a finally block in exception
handling?
The finally block is linked with a try block and contains a block of statements that
are executed irrespective of whether an exception occurs
or not within the try block.Finally defines the code that is executed always.
In the normal execution it is executed after the try block When an exception occurs,
it is executed after the handler if any or before propagation as the case may be.
What is custom exception and how to raise it in C#?
1. Custom exceptions can be defined as per requirement
2. Build the custom exception class by inheriting Exception class
3. To raise the custom exception at appropriate moment use throw myExcepObj;

1 class myException : Exception

2{

3 /*Implement the constructors by just calling the base class constructor*/

4 public myException() : base() {}

5 public myException( string msg ) : base(msg) {}

6}

Example:

1 using System;

2 class InvalidAgeException : Exception {

3 public InvalidAgeException() : base() {}

4 public InvalidAgeException(string msg) : base(msg)

5 {}

6 }

7 class Person {

8 private int age;

9 public int Age

10 {

11 set {
12 if ( value &gt;= 19 &amp;&amp; value &lt;= 60 )

13 age = value;

14 else{

15 InvalidAgeException

16 expObj = new InvalidAgeException("The Age input has to be with 19 to 60");

17 throw expObj;

18 }

19 }

20 get {

21 return age;

22 }

23 }

24 }

25 class Test {

26 public static void Main(string []args) {

27 Person personObj = new Person();

28 Console.Write("Enter the age : ");

29 try {

30 string ageInput = Console.ReadLine();

31 /* convert the string value into int value

32 with the help of int.parse() method */


33 personObj.Age = int.Parse( ageInput );

34 Console.WriteLine("Valid age input");

35 }

36 catch(InvalidAgeException expObj){

37 Console.WriteLine( expObj.Message );

38 }

39 }

40 }

What is the base class from which all the exceptions


are derived?
System.Exception

Does finally get executed if the code throws an


error?
Yes, Finally block will get executed always.

What is the difference between System exceptions


and Application exceptions?
System exceptions are derive directly from a base class System.SystemException. A
System level Exception is normally thrown when a nonrecoverable error has
occurred.
Application exceptions can be user defined exceptions thrown by the applications. If
you are designing an application that needs to create its own exceptions class, you
are advised to derive custom exceptions from the System.ApplicationException class.
It is typically thrown when a recoverable error has occurred.
What is the difference between throw and throw ex?
throw statement preserves original error stack information but in throw ex, stack
error of exception will be replaced with a stack trace starting with rethrow point.
Can abstract class have constructors in C#?
Yes, abstract class can have constructor in C#.

Can abstract class be Sealed in C#?


An abstract class cannot be a sealed class because the sealed modifier prevents a
class from being inherited and the abstract modifier requires a class to be inherited.

Can we declare abstract methods as private in C# ?


No. Abstract methods can not be private in C#.

Can abstract class have static methods in C#?


Yes, Abstract class can have static methods in C#.

Difference between abstract class and interface in


C#?
– An Abstract class doesn’t provide full abstraction but an interface does provide full
abstraction
– Using Abstract we can not achieve multiple inheritance but using an Interface we
can achieve multiple inheritance.
– We can not declare a member field in an Interface.
– We can not use any access modifier i.e. public , private , protected , internal etc.
because within an interface by default everything is public.
– An Interface member cannot be defined using the keyword static, virtual, abstract
or sealed

Can abstract class contain main method in C#?


Yes, Abstract class can contain main method in C#.

Does Abstract class support multiple Inheritance?


No, Abstract class does not support multiple Inheritance.

When to use Abstract class in C#?


Abstract methods are usually declared where two or more subclasses are expected
to do a similar thing in different ways through different implementations. These
subclasses extend the same Abstract class and provide different implementations for
the abstract methods.
Abstract classes are used to define generic types of behaviors at the top of an
object-oriented programming class hierarchy, and use its subclasses to provide
implementation details of the abstract class.

Abstract class must have only abstract methods.


True or false?
False. Abstract methods can have both abstract and non abstract methods.
Abstract keyword in C# :
Abstract classes are designed to be inherited from.An abstract class can only be used
as the base class of another class.

o You cannot create instances of an abstract class.


o An abstract class is declared using the abstract modifier
o An abstract class can contain abstract members or regular, nonabstract
members.
o The members of an abstract class can be any combination of abstract
members and normal members with implementations.
o An abstract class can itself be derived from another abstract class
o Any class derived from an abstract class must implement all the abstract
members of the class by using the override keyword,unless the derived class
is itself abstract.

Abstract members:
An abstract member is a function member that is designed to be overridden.An
abstract member has the following characteristics:

o It must be a function member. That is, fields and constants cannot be


abstract members.
o It must be marked with the abstract modifier.
o It must not have an implementation code block.The code of an abstract
member is represented by a semicolon.

Example:

1 abstract class AbstractClass // Abstract class

2 {
3 public void IdentifyBase() // Normal method

4 {

5 Console.WriteLine("I am Abstract Class");

6 }

7 abstract public void IdentifyDerived(); // Abstract method

8 }

9 class DerivedClass : AbstractClass // Derived class

10 {

11 override public void IdentifyDerived() // Implementation of

12 {

13 Console.WriteLine("I am Derived Class");

14 } // abstract method

15 }

16 class Program

17 {

18 static void Main()

19 {

20 // AbstractClass a = new AbstractClass(); // Error. Cannot instantiate

21 // a.IdentifyDerived(); // an abstract class.

22 DerivedClass b = new DerivedClass(); // Instantiate the derived class.

23 b.IdentifyBase(); // Call the inherited method.


24 b.IdentifyDerived(); // Call the "abstract" method.

25 }

26 }

Output:
I am Abstract Class
I am Derived Class

Virtual Keyword in C# :
Let’s look at the below example with new keyword:

1 class MyBaseClass

2 {

3 public void Print()

4 {

5 Console.WriteLine("This is the base class.");

6 }

7 }

8 class MyDerivedClass : MyBaseClass

9 {

10 new public void Print()

11 {

12 Console.WriteLine("This is the derived class.");

13 }
14 }

15 class Program

16 {

17 static void Main()

18 {

19 MyDerivedClass derivedclass = new MyDerivedClass();

20 MyBaseClass mybaseclass = (MyBaseClass)derivedclass;//Cast to base class

21 derivedclass.Print(); // Call Print from derived portion.

22 mybaseclass.Print(); // Call Print from base portion.

23 }

24 }

Output:
This is derived class
This is base class

In the above example, Main creates an object of type MyDerivedClass and stores its
reference in variable derivedclass.Main also creates a variable of type MyBaseClass
and uses it to store a reference to the base class portion of the object.When the
Print method is called on each reference, the call invokes the implementation of the
method that the reference can see,producing differentoutput strings.

you saw that when you access an object of a derived class by using a reference to
the base class, you get only the members from the base class. Virtual methods allow
a reference to the base class to access “up into” the derived class.
You can use a reference to a base class to call a method in the derived class if the
following are true:

o The method in the derived class and the method in the base class each have
the same signature and return type.
o The method in the base class is labeled virtual.
o The method in the derived class is labeled override.
Syntax:

1 class MyBaseClass // Base class

2{

3 virtual public void Print()

4 ...

5 class MyDerivedClass : MyBaseClass // Derived class

6{

7 override public void Print()

Let’s rewrite the above code using virtual and override.

1 class MyBaseClass

2 {

3 virtual public void Print()

4 {

5 Console.WriteLine("This is the base class.");

6 }

7 }

8 class MyDerivedClass : MyBaseClass

9 {

10 override public void Print()


11 {

12 Console.WriteLine("This is the derived class.");

13 }

14 }

15 class Program

16 {

17 static void Main()

18 {

19 MyDerivedClass derivedclass = new MyDerivedClass();

20 MyBaseClass mybaseclass = (MyBaseClass)derivedclass;

21 derivedclass.Print();

22 mybaseclass.Print();

23 }

24 }

Output:
This is the derived class.
This is the derived class.

When the Print method is called by using the reference to the base
class(mybaseclass),the method call is passed up to the derived class and executed,
because

o The method in the base class is marked as virtual.


o There is a matching override method in the derivedclass
Difference between Abstract and Virtual Function in
C# :

Summary:
In this article, we have discussed:

o Abstract keyword in C#?


o Virtual Keyword in C#
o Difference between Abstract and Virtual in C#
1. What is Enumeration in C#?
o An enum is a distinct value typewith a set of named constants
o It is declared by using keyword Enum
o Every Enum type has an underlying type which can be any integral type
except char. The default underlying type is int.
o The first enumerator has the value 0 by default and the value of each
successive enumerator is increased by 1
o Enumeration bridge the gap between numbers and objects

Example

1 enum colors

2 {

3 Red = 1,

4 Blue = 2,

5 Yellow = 3,

6 Green = 4

7 };

This code declares a colors enumeration containing four values.

2. How to convert Enum to String in C#?


You can convert Enum to String using ToString() method.

1 class Program

2 {

3 enum Colors { Red = 1, Pink = 2 };

4 static void Main(string[] args)


5 {

6 Enum myColors = Colors.Pink;

7 Console.WriteLine("The value of this instance is '{0}'",

8 myColors.ToString());

9 Console.ReadLine();

10 }

11 }

3. How to convert Enum to List in C#?


There are 2 ways of converting an Enum to a List in C#.

1 class Program

2 {

3 enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

5 static void Main(string[] args)

6 {

7 Array arr = Enum.GetValues(typeof(Days));

8 List<string> lstDays = new List<string>(arr.Length);

9 for (int i = 0; i < arr.Length; i++)

10 {

11 lstDays.Add(arr.GetValue(i).ToString());
12 }

13 }

14 }

Or

1 class Program

2 {

3 enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

5 static void Main(string[] args)

6 {

7 var lstDays = Enum.GetNames(typeof(Days));

8 }

9 }

4. How can you iterate through Enum values in C#?

1 class Program

2 {

3 public enum Colors

4 {

5 red,

6 blue,
7 green,

8 yellow

9 }

10 static void Main(string[] args)

11 {

12 foreach (Colors iColor in Enum.GetValues(typeof(Colors)))

13 {

14 Console.WriteLine(iColor.ToString());

15 }

16 }

17 }

5. How can an int value cast to Enum ?

1 class Program

2 {

3 enum Days

4 {

5 Sunday = 1,

6 TuesDay = 2,

7 wednesday = 3

8 }
9 static void Main(string[] args)

10 {

11 Days day = (Days)3;

12 Console.WriteLine(day);

13 }

14 }

or

1 class Program

2 {

3 enum Days

4 {

5 Sunday = 1,

6 TuesDay = 2,

7 wednesday = 3

8 }

9 static void Main(string[] args)

10 {

11 Days day = (Days)Enum.ToObject(typeof(Days), 3);

12 Console.WriteLine(day);

13 }
14 }

15 //Output: wednesday

6. How to get int value from Enum in C#?

1 class Program

2 {

3 enum Colors

4 {

5 Blue = 1,

6 Red = 2,

7 Yellow = 3,

8 Pink = 4

9 }

10 static void Main(string[] args)

11 {

12 int color = (int)Colors.Red;

13 Console.WriteLine(color);

14 }

15 }

16 //Output : 2
7.How to convert String to Enum in C#?

1 class Program

2 {

3 enum Colors

4 {

5 Blue,

6 Red,

7 Yellow,

8 Pink

9 }

10 static void Main(string[] args)

11 {

12 string inVal = "Red";

13 Colors newColor = (Colors)Enum.Parse(typeof(Colors), inVal);

14 //Check the Enum type

15 if (newColor == Colors.Red)

16 {

17 Console.WriteLine(newColor.ToString());

18 }

19 }

20 }
8. How to use Enum in Switch case in C# ?

1 class Program

2 {

3 enum Colors

4 {

5 Blue,

6 Red,

7 Yellow,

8 Pink

9 }

10 static void Main(string[] args)

11 {

12 Colors value = Colors.Yellow;

13 switch (value)

14 {

15 case Colors.Blue:

16 Console.WriteLine("Color is Blue");

17 break;

18 case Colors.Red:

19 Console.WriteLine("Color is Red");
20 break;

21 case Colors.Yellow:

22 Console.WriteLine("Color is Yellow");

23 break;

24 }

25 }

26 }
1. How will you specify what version of the
framework your application is targeting?
You can define “targetFramework” in Web.config file to specify the framework
version. It is introduced in Asp.net 4.0

1 <?xml version="1.0"?>

2 <configuration>

3 <system.web>

4 <compilation targetFramework="4.0" />

5 </system.web>

6 </configuration>

2. What is the difference between Static class and


Singleton instance?
– In c# a static class cannot implement an interface. When a single instance class
needs to implement an interface for some business reason or IoC purposes, you can
use the Singleton pattern without a static class.
– You can clone the object of Singleton but, you can not clone the static class object
– Singleton object stores in Heap but, static object stores in stack
– A singleton can be initialized lazily or asynchronously while a static class is
generally initialized when it is first loaded

3.What is the difference between Unicode,UTF,


ASCII and ANSI code format of encoding?
Character encoding interprets the zeros and ones into real characters.
Unicode:

Unicode is a standard that can handle characters for almost all modern languages
and even some ancient languages at the same time, as long as the client has fonts
for the particular language installed in his system

UTF:

Unicode assigns each character a unique number, or code point. It defines two
mapping methods, the UTF (Unicode Transformation Format) encodings, and the UCS
(Universal Character Set) encodings. Unicode-based encodings implement the
Unicode standard and include UTF-8, UTF-16 and UTF-32/UCS-4. They go beyond 8-
bits.

ASCII:

ASCII is abbreviated from American Standard Code for Information Interchange, is a


character encoding standard .ASCII codes represent text in computers.It is a code for
representing characters as numbers, with each letter assigned a number from 0 to
127.In an ASCII file, each alphabetic, numeric, or special character is represented
with a 7-bit binary number

ANSI:

ANSI is abbreviated from American National Standards Institute,is a character


encoding standard.ANSI includes all the ASCII characters with an additional 128
character codes. ASCII just defines a 7 bit code page with 128 symbols. ANSI extends
this to 8 bit and there are several different code pages for the symbols 128 to 255.

4. Can you serialize hashtable and Why?


No, You can’t Serialize Hash table.Because, the .NET Framework does not allow
serialization of any object that implements the IDictionary interface

5. What is .PDB file?


PDB is an abbreviation for Program Data Base. It is a repository (persistant storage as
databases) to maintain information required to run your program in debug mode. It
contains many important relevant information required while debugging your code;
for e.g. at what points you have inserted break points where you expect the
debugger to break in Visual Studio etc..
6. Why singleton pattern is considered an Anti-
pattern ?
– Singletons aren’t easy to handle with unit tests. You can’t control their
instantiation and they may retain state across invocations.
– Memory allocated to an Singleton can’t be freed.
– In multithreaded environment, access to the singleton object may have to be
guarded (e.g. via synchronization).
– Singletons promote tight coupling between classes, so it is hard to test

7. How to use Nullable Types in .NET?


Nullable types allow you to create a value type variable that can be marked as valid
or invalid so that you can make sure a variable is valid before using it. Regular value
types are called non-nullable types.

The important things you need to know about nullable type conversions are the
following:

• There is an implicit conversion between a non-nullable type and its nullable


version. That is, no cast is needed.
• There is an explicit conversion between a nullable type and its non-nullable
version.

For example, the following lines show conversion in both directions. In the first line,
a literal of type
int is implicitly converted to a value of type int? and is used to initialize the variable
of the nullable type.
In the second line, the variable is explicitly converted to its non-nullable version.

1 int? myInt1 = 15; // Implicitly convert int to int?

2 int regInt = (int) myInt1; // Explicitly convert int? to int

8. What are extension methods and where can we


use them?
Extension methods enables you to add new capabilities to an existing type. You
don’t need to make any modifications to the existing type, just bring the extension
method into scope and you can call it like a regular instance method.
Extension methods need to be declared in a nongeneric, non-nested, static class.

Notes:
o The difference between a regular static method and an extension method is
the special this keyword for the first argument.
o Extension method cannot be declared on a class or struct.
o It can also be declared on an interface (such as IEnumerable). Normally, an
interface wouldn’t have any implementation. With extension methods,
however, you can add methods that will be available on every concrete
implementation of the interface
o Language Integrated Query (LINQ) is one of the best examples of how you can
use this technique to enhance existing code.

You can read the implementation of Extension Methods in C# here.

9. How to implement singleton design pattern in C#?


There are several ways for implementing Singleton in C#.

o Standard Implementation
o Double checked locking
o Early Instance Creation
o Fully Lazy Instantiation
o Using Generics
o using Lazy<T> type

You can read each way of Singleton Implementation here.

10.What is difference between the “throw” and


“throw ex” in .NET?
throw re-throws the exception that was caught, and preserves the stack trace. throw
ex throws the same exception, but resets the stack trace to that method.Unless you
want to reset the stack trace (i.e. to shield public callers from the internal workings
of your library), throw is generally the better choice, since you can see where the
exception originated.

Throw Syntax:

1 try

2{
3 // do some operation that can fail

4}

5 catch (Exception ex)

6{

7 // do some local cleanup

8 throw;

9}

Throw ex Syntax:

1 try

2 {

3 // do some operation that can fail

4 }

5 catch (Exception ex)

6 {

7 // do some local cleanup

8 throw ex;

9 }

10 }
1. How to update web.config programatically?
This file is an XML file, and reading/writing XML is supported by .NET. You can
choose one of the method as per your requirement:

o Use System.Xml.XmlDocument class. It implements DOM interface; this way is


the easiest and good enough if the size of the document is not too big.
o Use the classes System.Xml.XmlTextWriter and System.Xml.XmlTextReader;
this is the fastest way of reading
o Use the class System.Xml.Linq.XDocument; this is to support LINQ to XML
Programming.

2. What is the difference between Stack and Heap


memory in C#?
3. What is the difference between covariance and
contravariance?
You can read the detailed article on covariance and contravariance here.

4. What are indexers in C# .NET? What is the


difference between property & indexers?
An indexer is a pair of get and set accessors, similar to those of properties.

o Like a property, an indexer does not allocate memory for storage.


o Both indexers and properties are used primarily for giving access to other
data members with which they are associated and for which they provide get
and set access.
− A property usually represents a single data member.
− An indexer usually represents multiple data members.
o Like a property, an indexer can have either one or both of the accessors.
o Indexers are always instance members; hence, an indexer cannot be declared
static.
o Like properties, the code implementing the get and set accessors does not
have to be associated with any fields or properties. The code can do
anything, or nothing, as long as the get accessor returns some value of the
specified type.

5. How to create array with non-default value in C#?


You can create array with non-default value in C# using Enumerable.Repeat.

bool[] boolArray = Enumerable.Repeat(true, 13).ToArray(); // creates bool array of


size 13 with default value “true”
int[] intArray = Enumerable.Repeat(12, 35).ToArray(); // creates int array of size 35
with default value “12”
string[] strArray = Enumerable.Repeat(“Welcome”, 6).ToArray();// creates string
array of size 6 with default value “Welcome”

6. What’s difference between delegate and events?


An event is just a wrapper for a multicast delegate.
Adding a public event to a class is almost the same as adding a public multicast
delegate field.
In both cases, subscriber objects can register for notifications, and in both cases the
publisher object can send notifications to the subscribers. However, a public
multicast delegate has the undesirable property that external objects can invoke the
delegate, something we’d normally want to restrict to the publisher. Hence events –
an event adds public methods to the containing class to add and remove receivers,
but does not make the invocation mechanism public.

7. Can we Overload main() method in C#?


Yes, We can overload main() method. A C# class can have any number of main()
methods.
But to run the C# class, class should have main() method with signature as “public
static void main(String[] args)”. If you do any modification to this signature,
compilation will be successful. But, You will get run time error as main method not
found.

8. What are the differences between Dispose and


Finalize ?

9. How to design a class (or data type) which sorts


its data either ascending or descending by default
You can do this by using Array.BinarySearch. Below is the implementation in C#.

1 class Program

2 {

3 static void Main(string[] args)

4 {
5 MySortedList list = new MySortedList();

6 list.Add(13);

7 list.Add(81);

8 list.Add(25);

9 list.Add(9);

10 list.Add(33);

11 list.Add(46);

12 list.Add(1);

13 foreach (int v in list.Items)

14 {

15 Console.WriteLine(v);

16 }

17 Console.ReadLine();

18 }

19 }

20

21 class MySortedList

22 {

23 int[] items = new int[0];

24 public int[] Items

25 {
26 get { return items; }

27 set { items = value; }

28 }

29

30 public void Add(int value)

31 {

32 int index = Array.BinarySearch(items, value);

33 if (index < 0)

34 index = ~index;

35

36 //Increase Items Array Size by 1

37 int lastIndex = items.Length;

38 int capacity = items.Length + 1;

39 int[] dupArray = new int[capacity];

40 Array.Copy(items, dupArray, items.Length);

41 items = dupArray;

42

43 //Adjusting elements to insert element in its right index

44 if (index < lastIndex)

45 {

46 Array.Copy(items, index, items, index + 1, lastIndex - index);


47 }

48 items[index] = value;

49 }

50 }

You have a component with 5 parameters and


deployed to client side now you changed your
method which takes 6 parameters. How can you
deploy this without affecting the client’s code?
Instead of adding 6th parameter to the existing method, write new overloaded
method with 6 parameters.

So when old application calls this method, method with 5 parameter will execute.
And method with 6 parameter will be used by new application. That way we can
provide backward compatibility to old application.
1. What is Satellite Assembly?
A satellite assembly is a compiled library (DLL) that contains “localizable” resources
specific to a given culture such as strings, bitmaps, etc. You are likely to use
satellite assemblies when creating a multilingual UI application.

As per MSDN definition, A .NET Framework assembly containing resources specific to


a given language. Using satellite assemblies, you can place the resources for
different languages in different assemblies, and the correct assembly is loaded into
memory only if the user elects to view the application in that language.

2. What is Object Pooling in C#?


Object Pool is a container of objects that are ready for use. Whenever there is a
request for a new object, the pool manager will take the request and it will be
served by allocating an object from the pool.So it reduces the load of object
creation.

3. Explain the difference between Error and


Exception in C#?
Exception handling is a mechanism to detect and handle error at run time where as
Errors are occured at development/compile time.
You can read more on exception handling in C# here.

4. What is the difference between == and .Equals


method in c#?
int x = 20;

int y = 20;

Console.WriteLine( x == y);

Console.WriteLine(x.Equals(y));

Output:

True
True

For Reference Type:


== performs an identity comparison, i.e. it will only return true if both references
point to the same object. While Equals() method is expected to perform a value
comparison, i.e. it will return true if the references point to objects that are
equivalent.

For Example:
StringBuilder s1 = new StringBuilder(“Yes”);

StringBuilder s2 = new StringBuilder(“Yes”);

Console.WriteLine(s1 == s2);

Console.WriteLine(s1.Equals(s2));

Output:

False

True

In above example, s1 and s2 are different objects hence “==” returns false, but they
are equivalent hence “Equals()” method returns true. Remember there is an
exception of this rule, i.e. when you use “==” operator with string class it compares
value rather than identity.

When to use “==” operator and when to use “.Equals()” method?

For value comparison, with Value Type use “==” operator and use “Equals()” method
while performing value comparison with Reference Type.

5. What is Partial class and What all are the


advantages of Partial class?
The class declaration can be partitioned into several partial class declarations.

o Each of the partial class declarations contains the declarations of some of the
class members.
o The partial class declarations of a class can be in the same file or in different
files.
o Each partial declaration must be labeled as partial class,in contrast to the
single keyword class.
Advantages of Partial Class:

By Using Partial Classes, multiple developer can work on the same class easily.
Partial classes are mainly used by code generator to keep different concerns
separate
you can also define Partial methods as well where a developer can simply define the
method and the other developer can implement that.

6. What all are the Advantages and Disadvantages of


Generics in C#?
Advantages of Generics:
o Generics provide type safety without the overhead of multiple
implementations.
o Generics eliminates boxing and unboxing.
o There is no need to write code to test for the correct data type because it is
enforced at compile time. The need for type casting and the possibility of
run-time errors are reduced.
o By providing strong typing, a class built from a generic lets visual studio
provide IntelliSense.
o Generic collection types generally perform better for storing and
manipulating value types because there is no need to box the value types
o Generic delegates enable type-safe callbacks without the need to create
multiple delegate classes.
Disdvantages of Generics:
 Generic types can be derived from most base classes, such as MarshalByRefObject (and
constraints can be used to require that generic type parameters derive from base classes like
MarshalByRefObject). However, the .NET Framework does not support context-bound generic
types. A generic type can be derived from ContextBoundObject, but trying to create an instance of
that type causes a TypeLoadException.

 Enumerations cannot have generic type parameters.

 Lightweight dynamic methods cannot be generic.

 In C#, a nested type that is enclosed in a generic type cannot be instantiated unless types have
been assigned to the type parameters of all enclosing types

7. Why C# main method is static?


The C# main method is static because object is not required to call static method if
it were non-static method, compiler creates object first then call main() method
that will lead the problem of extra memory allocation.

8. What is Implementation Inheritance and Interface


Inheritance?
Implementation inheritance:

– It is achieved when a class is derived from another class in such a way that it
inherits all its members.
– It is called as Class Inheritance.
– In this, it uses ‘extends’ keyword in Java.
– The subclass is tightly coupled with superclass.
– If there is any changes to superclass will break the whole relationship.

Interface inheritance:

– It is achieved when a class inherits only the signatures of the functions from
another class.
– It is called as Type inheritance and also called as subtyping.
– In this, it uses ‘implements’ keyword in Java.
– It is used for code reuse and polymorphism.
– It reduces coupling and implementation dependencies.

9. What is Assembly Manifest?


Within every Assembly there is an Assembly Manifest. It contains:
-The assembly’s identity (its name and version).
-A file table describing all the other files that make up the assembly, for example,
any other assemblies you created that your .exe or .dll file relies on, or even bitmap
or Readme files.
-An assembly reference list, which is a list of all external dependencies—.dlls or
other files your application needs that may have been created by someone else.
Assembly references contain references to both global and private objects. Global
objects reside in the global assembly cache.

10. What is Reflection and what all are the common


use of Reflection?
Reflection is a process by which a program can examine and manipulate program
objects at run time.
Common use of Reflection:

– Load assemblies at runtime


– it allows you to learn what assembly defines a particular item such as a class or
enumeration
– List a class’s field,properties, constructors, event and methods
– Get information about a property such as type and if it is read only
– Get and Set property’s value
– Get information about item’s attribute etc..
1. What is Encapsulation and Data hiding in C#?
– Encapsulation is a process of hiding the members from outside of class and
implemented using access specifiers
– Encapsulation is also called as information hiding.
– Encapsulation provides a way to preserve the integrity of state data. Rather than
defining public fields, private data fields should be defined.
– Well-encapsulated class should hide its data and the details of how it operates on
data from the outside world. This is termed black box programming.
– Using this,implementation of the method can be changed by the class author
without breaking any existing code making use of it.

2. What does the tilde (~) mean in C#?


The ~ operator performs a bitwise complement operation on its operand, which has
the effect of reversing each bit. Bitwise complement operators are predefined for
int, uint, long, and ulong. Also the ~ symbol is used to declare destructors.

You can read more on tilde(~) here.

3. Can you use tilde(~) with Enum in C# ?


Yes, You can use tilde(~) with Enum to flips the bits of its operand.

1 //using tilde(~)

2 [Flags]

3 public enum PurchaseMethod

4 {

5 All = ~0,

6 None = 0,

7 Cash = 1,

8 Check = 2,

9 CreditCard = 4

10 }

11 //Alternative:

12 [Flags]
13 public enum PurchaseMethod

14 {

15 None = 0,

16 Cash = 1,

17 Check = 2,

18 CreditCard = 4,

19 All = Cash | Check | CreditCard

20 }

– Source: Stack Overflow

4. What does placing a @ in front of a C# variable


name do?
It’s a way to allow declaring reserved keywords as vars.
Example:

1 void test(int @string)

5. How do you give a C# Auto-Property a default


value?
In C#5 and earlier, you can do it using constructor.

1 class Employee

2{

3 public Employee()

4 {

5 Name = "Default Name";

6 }
7 public string Name { get; set; }

8}

In C#6.0, You can do:

1 public string Name { get; set; } = "Default Name"

6. What is the use of Yield keyword in C#?


Yield keyword helps us to do custom stateful iteration over .NET collections.
There are two scenarios where “yield” keyword is useful:-
– It helps to provide custom iteration without creating temp collections.
– It helps to do state-full iteration

You can read more on Yield keyword here.

7. What is AsyncCallback in C#?


When the async method finishes the processing, AsyncCallback method is
automatically called, where post processing stmts can be executed. With this
technique there is no need to poll or wait for the async thread to complete.

8. What is Nested types in C# and how to use it?


Types are usually declared directly inside a namespace. You can, however, also
declare types inside a class or struct declaration.
– Types declared inside another type declaration are called nested types. Like all
type declarations, nested types are templates for an instance of the type.
– A nested type is declared like a member of the enclosing type.
– A nested type can be any type.
– An enclosing type can be either a class or a struct.

For example, the following code shows class MyClass, with a nested class called
MyCounter.

1 class MyClass // Enclosing class

2 {
3 class MyCounter // Nested class

4 {

5 ...

6 }

7 ...

8 }

It is good to use Nested types if it is only meant to be used as a helper for the
enclosing type.

9. What is an Attribute in C#?


An attribute is a language construct that allows you to add metadata to a program’s
assembly. It’s a special type of class for storing information about program
constructs.
– The program construct to which you apply an attribute is called its target.
– Programs designed to retrieve and use metadata, such as object browsers, are said
to be consumers of the attributes.
– There are attributes that are predefined in .NET, and you can also declare custom
attributes.

10. What is Null Coalescing Operator in C#?


C# Supports a special operator called the null coalescing operator, which returns a
non-null value to an expression, in case a nullable type variable is null.
The null coalescing operator consists of two contiguous question marks and has two
operands.
– The first operand is a variable of a nullable type.
– The second is a non-nullable value of the underlying type.
– If, at run time, the first operand (the nullable operand) evaluates to null, the
nonnullable operand is returned as the result of the expression.
Example:

1 int? myI4 = null;

2 Console.WriteLine("myI4: {0}", myI4 ?? -1);

3 myI4 = 10;

4 Console.WriteLine("myI4: {0}", myI4 ?? -1);


This code produces the following output:

1 myI4: -1

2 myI4: 10
1. What are weakreferences in C#?How is it different
than StrongReferences
The garbage collector cannot collect an object in use by an application while the
application’s code can reach that object. The application is said to have a strong
reference to the object.
A weak reference permits the garbage collector to collect the object while still
allowing the application to access the object. A weak reference is valid only during
the indeterminate amount of time until the object is collected when no strong
references exist. When you use a weak reference, the application can still obtain a
strong reference to the object, which prevents it from being collected. However,
there is always the risk that the garbage collector will get to the object first before
a strong reference is re-established.

Weak references are useful for objects that use a lot of memory, but can be
recreated easily if they are reclaimed by garbage collection

2. What are XML namespaces for?


XML namespaces are like packages in C#.They are for allowing multiple markup
languages to be combined, without having to worry about conflicts of element and
attribute names.
– You can reuse a set of tags/attributes you define across different types of xml
documents.
– If you need to add some “aspect” to your XML; adding a namespace to your xml
document is simpler than changing your whole xml schema definition.
– Avoid poluting the “main” namespace: You don’t force your parser to work with a
huge schema definition, just use the namespace you need to.

3. What is the difference between string and String


in C# ?
String stands for System.String and it is a .NET Framework type. string is an alias in
the C# language for System.String. Both of them are compiled to System.String in IL
(Intermediate Language), so there is no difference.

4. What’s the difference between the ‘ref’ and ‘out’


keywords in C#?
The ref modifier means that:
– The value is already set and
– The method can read and modify it.
The out modifier means that:
– The Value isn’t set and can’t be read by the method until it is set.
– The method must set it before returning.

semantically, ref provides both “in” and “out” functionality, whereas out only
provides “out” functionality.
You can read the difference between value type and reference type here.

5. What is the difference between Debug.Write and


Trace.Write in C#?
– The Debug.Write will work when the application is in both debug and release
mode.This is normally used while you debug your project but it won’t work if you
have defined few debug points in your project.
– The Trace.Write will work when the application is in release mode.This is used in
release version of application and will be compiled while you define debug points in
your project.
– Trace.Write and Debug.Write sends their output to the same destinations, as
defined by the TraceListenersCollection.
– Debug.Write is used at application development time and Trace.Write is used at
application deployment time
– If ‘TRACE’ is defined during the compilation, Trace.Write will be emitted. If
‘DEBUG’ is defined during the compilation, Debug.Write will be emitted

6. What is the difference between


myEmployee.GetType() and typeof(Employee) in C#?
The result of both would be exactly the same.It will be your Employee type that
derives from System.Type. The only real difference here is that when you want to
obtain the type from an instance of your class, you use GetType. If you don’t have
an instance, but you know the type name, you would use typeof.
GetType gets resolved at runtime, while typeof is resolved at compile time.

7. What is the difference between an EXE and a DLL?


EXE:
– Executable file, can run independently
– It runs in a separate process
– It can’t be reused in application
– it has a main function
DLL:
– Dynamic link library is used as part of EXE or other DLL’s
– It runs in application process memory,
– It can be reused in application
– It does not have a main function

8. What are the advantages and disadvantages of


using the GAC?
– GAC is a central repository in a system in which assemblies are registered to shared
between application.
– GACUtil.exe is used to view and change the content of GAC in system
– GAC can contain multiple versions on .net assemblies
– Thegautil.exe/I is used to install assembly in GAC

Advantages & Disadvantages:


– Loading assemblies from GAC mean less overhead and security that your
application will always load correct version of .NET library
– You shouldn’t ngen assemblies that are outside of GAC, because there will be
almost no performance gain, in many cases even loss in performance.
– You’re already using GAC, because all standard .NET assemblies are actually in GAC
and ngened (during installation).
– Using GAC for your own libraries adds complexity into deployment, I would try to
avoid it at all costs.
– Your users need to be logged as administrators during installation if you want to
put something into GAC, quite a problem for many types of applications.

9. What is the difference between a process and a


thread?
Process:
– An executing instance of a program is called a process.
– Some operating systems use the term ‘task‘ to refer to a program that is being
executed.
– A process is always stored in the main memory also termed as the primary memory
or random access memory.
– Therefore, a process is termed as an active entity. It disappears if the machine is
rebooted.
– Several process may be associated with a same program.
– On a multiprocessor system, multiple processes can be executed in parallel.
– On a uni-processor system, though true parallelism is not achieved, a process
scheduling algorithm is applied and the processor is scheduled to execute each
process one at a time yielding an illusion of concurrency.
Thread:
– A thread is a subset of the process.
– It is termed as a ‘lightweight process’, since it is similar to a real process but
executes within the context of a process and shares the same resources allotted to
the process by the kernel.
– Usually, a process has only one thread of control – one set of machine instructions
executing at a time.
– A process may also be made up of multiple threads of execution that execute
instructions concurrently.
– Multiple threads of control can exploit the true parallelism possible on
multiprocessor systems.
– On a uni-processor system, a thread scheduling algorithm is applied and the
processor is scheduled to run each thread one at a time.
– All the threads running within a process share the same address space, file
descriptors, stack and other process related attributes.
– Since the threads of a process share the same memory, synchronizing the access to
the shared data withing the process gains unprecedented importance.

– Source: Knowledge Quest

10. If asynchronous execution takes less total time


to finish than synchronous execution, why would
anybody choose synchronous execution?
In Synchronus mode, every task executes in sequence, so it’s easier to program.
That’s the way we’ve been doing it for years.

With asynchronous execution, you have few challenges:


– You must synchronize tasks. for e.g. you run a task that must be executed after the
other three have finished. You will have to create a mechanism to wait for all tasks
to finish before launching the new task.
– You must address concurrency issues. If you have a shared resource, like a list that
is written in one task and read in another, make sure that it’s kept in a known state.
– There is no logical sequence anymore. The tasks can end at any time, and you
don’t have control of which one finishes first.

But in synchronous programming we have below disadvantages:


– It takes longer to finish.
– It may stop the user interface (UI) thread. Typically, these programs have only one
UI thread, and when you use it as a blocking operation, you get the spinning wheel
(and “not responding” in the caption title) in your program—not the best experience
for your users.
It doesn’t use the multicore architecture of the new processors. Regardless of
whether your program is running on a 1-core or a 64-core processor, – it will run as
quickly (or slowly) on both.
Asynchronous programming eliminates these disadvantages: it won’t hang the UI
thread (because it can run as a background task), and it can use all the cores in your
machine and make better use of machine resources. So, do you choose easier
programming or better use of resources? Fortunately, you don’t have to make this
decision. Microsoft has created several ways to minimize the difficulties of
programming for asynchronous execution.
1. Why do we need C# delegates?
you can call methods directly on the object but in below scenarios you may consider
using Delegates:
– You want to call series of method by using single delegate without writing lot of
method calls.
– You want to implement event based system elegantly.
– You want to call two methods same in signature but reside in different classes.
– You want to pass method as a parameter.
– You don’t want to write lot of polymorphic code like in LINQ , you can provide lot
of implementation to the Select method.

2. why do we use the Dictionary class instead of the


Hashtable class?
Dictionary is a generic type, Hashtable is not. That means you get type safety with
Dictionary, because you can’t insert any random object into it, and you don’t have
to cast the values you take out.

Hashtable supports multiple reader threads with a single writer thread, while
Dictionary offers no thread safety. If you need thread safety with a generic
dictionary, you must implement your own synchronization.

3. Are nullable types reference types in C# ?


Nullable types are instances of the System.Nullable struct.Nullable types represent
value-type variables that can be assigned the value of null. You cannot create a
nullable type based on a reference type. So nullable types are not reference types.

4. What is the difference between System


exceptions and Application exceptions?
System exceptions are derived directly from a base class System.SystemException. A
System level Exception is normally thrown when a nonrecoverable error has
occurred.
Application exceptions can be user defined exceptions thrown by the applications. If
you are designing an application that needs to create its own exceptions class, you
are advised to derive custom exceptions from the System.ApplicationException class.
It is typically thrown when a recoverable error has occurred.
5. What is the difference between Var and Dynamics
in C#?

6. When to use Tuples in C#?


Tuples are commonly used in four ways:

– To represent a single set of data. For example, a tuple can represent a database
record, and its components can represent individual fields of the record.
– To provide easy access to, and manipulation of, a data set.
– To return multiple values from a method without using out parameters
– To pass multiple values to a method through a single parameter. For example, the
Thread.Start(Object) method has a single parameter that lets you supply one value
to the method that the thread executes at startup time. If you supply a Tuple object
as the method argument, you can supply the thread’s startup routine with three
items of data.
7. How can you create responsive UI without
impacting users?
You can create a responsive UI using multithreading. You can split the work into
small pieces and run it in background without impacting user.

8. What is Race condition in C#?


when two or more threads are able to access shared data and they try to change it
at the same time. Because the thread scheduling algorithm can swap between
threads at any point, we cannot know the order at which the threads will attempt to
access the shared data. Therefore, the result of the change in data is dependent on
the thread scheduling algorithm, i.e. both threads are ‘racing’ to access/change the
data. The reason for having more race conditions among threads than processes is
that threads can share their memory while a process can not.

9. How to Force Garbage Collection?


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

1 StreamWriter stream = File.CreateText(“temp.dat”);

2 stream.Write(“some test data”);

3 GC.Collect();

4 GC.WaitForPendingFinalizers();

5 File.Delete(“temp.dat”);

10. What is the difference between Lock and


Monitor in C#?
Monitor and lock is the way to provide thread safety in a multithreaded application
in C#.Lock is the keyword in C# that will ensure one thread is executing a piece of
code at one time. The lock keyword ensures that one thread does not enter a critical
section of code while another thread is in that critical section.
1. Why do we need Reflection in C#?
We use Reflection in C#:
– Load assemblies at runtime
– it allows you to learn what assembly defines a particular item such as a class or
enumeration
– List a class’s field,properties, constructors, event and methods
– Get information about a property such as type and if it is read only
– Get and Set property’s value
– Get information about item’s attribute etc..

2. How do you mark a method as


Obsolete/Deprecated?
You can use Obsolete attribute to mark a method as Obsolete or Deprecated.

1 [Obsolete]

2 //You can add an explanation:

3 [Obsolete("Method1 is deprecated, please use Method2 instead.")]

4 //You can also cause the compilation to fail if the method is called from somewhere in code like this:

5 [Obsolete("Method1 is deprecated, please use Method2 instead.", true)]

3. Can you use ref and out parameters in Lambda


expression, if declared outside?
If you will use ref or out parameter outside of Lamda Expression then you will get
compile time error.

1 static void DoWork(int valIn, out int valOut)

2 {

3 int local;

5 Action doCalc = () =>

6 {
7 local = valIn * 2; // this will work fine

8 //valOut = valIn * i; // this will be a compile time error

9 };

10

11 // you can use the out parameter to assign result of lambda

12 Func<int> doCalc2 = () => valIn * 2;

13 valOut = doCalc2(); // Allowed

14 }

4. How to return multiple values from a function in


C#?
In C#, There are several ways to return multiple values from a C# function.

– Using KeyValue pair


– Using ref/out parameters
– Using Struct or Class
– Using Tuple

You can read the detailed article here.

5. What all are the differences between Rectangular


and Jagged Array in C#
The structure of rectangular and jagged arrays is significantly different.One-
dimensional arrays have specific instructions in the CIL that allow them to be
optimized for performance. Rectangular arrays do not have these instructions and
are not optimized to the same level.
It is more efficient to use jagged arrays of one-dimensional arrays—which can be
optimized—than rectangular arrays.On the other hand, the programming complexity
can be significantly less for a rectangular array because it can be treated as a single
unit, rather than an array of arrays.

In above diagram, the structure of a rectangular three-by-three array, as well as a


jagged array of three one-dimensional arrays of length 3.
-Both arrays hold nine integers, but as you can see, their structures are quite
different.
-The rectangular array has a single array object, while the jagged array has four
array objects.

6. How can you cancel an Async operation in C#?


You can cancel your own async operation.There are two classes in the
System.Threading.Tasks namespace that are designed for this purpose:
CancellationToken and CancellationTokenSource.

A CancellationToken object contains the information about whether a task should be


cancelled or not.
A task that has a CancellationToken object needs to periodically inspect it to see
what the token’s state is. If the CancellationToken object’s
IsCancellationRequested property is set to true, the task should halt its operations
and return.
A CancellationToken is nonreversible and can only be used once. That is, once it’s
IsCancellationRequested property is set to true, it can’t be changed.
A CancellationTokenSource object creates a CancellationToken object, which can
then be given to various tasks. Any objects holding a cancellationTokenSource can
call its Cancel method, which sets the CancellationToken’s IsCancellationRequested
property to true.

You can read more on Async and await here.

7. Can abstract class be Sealed in C#?


An abstract class cannot be a sealed class because the sealed modifier prevents a
class from being inherited and the abstract modifier requires a class to be inherited.

8. What is the main use of a finally block in


exception handling?
The finally block is linked with a try block and contains a block of statements that
are executed irrespective of whether an exception occurs
or not within the try block.Finally defines the code that is executed always.
In the normal execution it is executed after the try block When an exception occurs,
it is executed after the handler if any or before propagation as the case may be.

9. How to avoid Singleton instance creation by


cloning ?
We can create a copy of an object using clone() method.

To avoid creating a clone of our singleton class, we can do the following :


– Implement MethodwiseClone()
– Override the clone() method and throw CloneNotSupportedException from it.

1 protected object MemberwiseClone()

2 {

3 throw new Exception("Cloning a singleton object is not allowed");

4 }

10. What are generations in GC?


After the garbage collector is initialized by the CLR, it allocates a segment of
memory to store and manage objects.

This memory is called the managed heap, as opposed to a native heap in the
operating system.

There is a managed heap for each managed process. All threads in the process
allocate memory for objects on the same heap.

The heap is organized into generations so it can handle long-lived and short-lived
objects. Garbage collection primarily occurs with the reclamation of short-lived
objects that typically occupy only a small part of the heap. There are three
generations of objects on the heap:

Generation 0. This is the youngest generation and contains short-lived objects. An


example of a short-lived object is a temporary variable. Garbage collection occurs
most frequently in this generation.

Newly allocated objects form a new generation of objects and are implicitly
generation 0 collections, unless they are large objects, in which case they go on the
large object heap in a generation 2 collection.

Most objects are reclaimed for garbage collection in generation 0 and do not survive
to the next generation.
Generation 1. This generation contains short-lived objects and serves as a buffer
between short-lived objects and long-lived objects.
Generation 2. This generation contains long-lived objects. An example of a long-
lived object is an object in a server application that contains static data that is live
for the duration of the process.

Garbage collections occur on specific generations as conditions warrant. Collecting a


generation means collecting objects in that generation and all its younger
generations. A generation 2 garbage collection is also known as a full garbage
collection, because it reclaims all objects in all generations (that is, all objects in
the managed heap).

Generation 0 – Short-lived Objects


Generation 1- As a buffer between short lived and long lived objects
Generation 2 – Long lived objects
1. How to catch multiple exceptions at once in C#?
You can catch multiple exceptions using condition statements in C#.
Example:

1 catch (Exception ex)

2 {

3 if (ex is FormatException || ex is OverflowException)

4 {

5 testid = "";

6 return;

7 }

9 throw;

10 }

In C#6.0,

1 catch (Exception ex) when (ex is FormatException || ex is OverflowException)

2{

3 testid = "";

4 return;

5}

2. Write a Regular expression to validate email


address?
^[a-zA – Z0 – 9. _%+-]+@[a-zA – Z0-9 . _%+-]+\.[a-zA-Z]{2,4}$
In the above example:
– the sequence ^[a-zA – Z0 – 9. _%+-] matches letters,digits,underscores,%,+ and -.
– The + (plus) sign after the 1st sequence means the string must include one or more
of those characters
– Next the pattern matches @
– Then the pattern matches another letter one or more times followed by a . and
then between two to four letters
3. Can you loop through all Enum values in C#?
Yes, you can loop through all Enum values using GetValues or the typed version.

1 public enum Color {

2 Red,

3 Blue,

4 Black,

5 White

6 }

7 var values = Enum.GetValues(typeof(Colors));

8 //Or the typed version

9 var values = Enum.GetValues(typeof(Colors)).Cast<Colors>();

4. Should ‘using’ statements be inside or outside the


namespace in C#?
Let’s look at below example to understand the difference of ‘using’ statements
inside or outside the namespace.
suppose there are 2 files.

1 // File1.cs

2 using System;

3 namespace Outer.Inner

4 {

5 class Foo

6 {

7 static void Bar()

8 {

9 double d = Math.PI;

10 }
11 }

12 }

13

14 // File2.cs

15 namespace Outer

16 {

17 class Math

18 {

19 }

20 }

The compiler searches Outer before looking at those using statements outside the
namespace, so it finds Outer.Math instead of System.Math. Outer.Math has no PI
member, so File1 is now broken.

This changes if you put the “using” inside your namespace declaration, as follows:

1 // File1b.cs

2 namespace Outer.Inner

3 {

4 using System;

5 class Foo

6 {

7 static void Bar()

8 {

9 double d = Math.PI;

10 }

11 }

12 }

Now the compiler searches ‘System’ before searching ‘Outer’, finds ‘System.Math’.
So this will work fine.
5. Should a return statement be inside or outside a
lock statement?
Whether you put the return statement inside or outside a lock statement, It doesn’t
make any difference; they’re both translated to the same thing by the compiler.

1 void example() {

2 int testData;

3 lock (foo) {

4 testData = ...;

5 }

6 return testData

7}

vs.

1 void example() {

2 lock (foo) {

3 return ...;

4 }

5}

It is recommended to put the return inside the lock. Otherwise you risk another
thread entering the lock and modifying your variable before the return statement,
therefore making the original caller receive a different value than expected.

6. How to iterate over a Dictionary in C#?


You can use keyValue pair to iterate over a dictionary in C#.

1 foreach(KeyValuePair<string, string> entry in myDic)

2{

3 // do something with entry.Value or entry.Key

4}
If you are trying to use a generic Dictionary in C# like you would use an associative
array in another language:

1 foreach(var item in myDictionary)

2{

3 foo(item.Key);

4 bar(item.Value);

5}

Or, if you only need to iterate over the collection of keys, use

1 foreach(var item in myDictionary.Keys)

2{

3 foo(item);

4}

And lastly, if you’re only interested in the values:

1 foreach(var item in myDictionary.Values)

2{

3 foo(item);

4}

7. What is the use of the IDisposable interface in C#


The primary use of the IDisposable interface is to clean up unmanaged
resources.”unmanaged” means things like database connections, sockets, window
handles, etc.The garbage collector doesn’t know how to call DeleteHandle() on a
variable of type IntPtr, it doesn’t know whether or not it needs to call
DeleteHandle().

So Microsoft has faciliated the Idisposable Interface and Dispose method to clean up
unmanaged resources.

Implement IDisposable and Dispose method:


1 using System;

2 using System.IO;

3 class UnmangedWrapper : IDisposable

4 {

5 public FileStream Stream { get; private set; }

6 public UnmangedWrapper()

7 {

8 this.Stream = File.Open(“temp.dat”, FileMode.Create);

9 }

10 ~UnmangedWrapper()

11 {

12 Dispose(false);

13 }

14 public void Close()

15 {

16 Dispose();

17 }

18 public void Dispose()

19 {

20 Dispose(true);

21 System.GC.SuppressFinalize(this);

22 }

23 public void Dispose(bool disposing)

24 {

25 if (disposing)

26 {

27 if (Stream != null)

28 {

29 Stream.Close();
30 }

31 }

32 }

33 }

8. How do you give a C# Auto-Property a default


value?
In C#5 or below:

1 class Person

2 {

3 public Person()

4 {

5 //do anything before variable assignment

7 //assign initial values

8 Name = "Default Name";

10 //do anything after variable assignment

11 }

12 public string Name { get; set; }

13 }

In C#6.0, it is much simpler.

1 public string Name { get; set; } = "Default Name"


9. What all are the difference between Dictionary
class and Hashtable class?

10. When to use struct instead of class in C#?


Consider defining a structure instead of a class if instances of the type are small and
commonly short-lived or are commonly embedded in other objects.
Do not define a structure unless the type has all of the following characteristics:
– It logically represents a single value, similar to primitive types (integer, double,
and so on).
– It has an instance size smaller than 16 bytes.
– It is immutable.
– It will not have to be boxed frequently.
1. How do you generate a random number in C#?
The Random class is used to create random numbers in C#.

1 //Example:

2 Random r = new Random();

3 int n = r.Next();

2. How to split string using Regex in C#?


The Regular Expressions Split() methods are similar to the String.Split() method,
except that Regex.Split() method splits the string at a delimiter determined by a
Regular Expression instead of a set of characters.

When using Regular Expressions you should use the following namespace:

1 using System.Text.RegularExpressions;

2 string str = "test1\n \ntest2\n \ntest3\n \n \ntest4";

3 string[] result = Regex.Split(str, "\n\\s*");

4 for (int i = 0; i < result.Length; i++)

5 MessageBox.Show(result[i]);

7 //Output:

8 test1

9 test2

10 test3

11 test4

3. How can you get the assembly version in C#?


You can get the assembly version in C#:

1 Version version = Assembly.GetEntryAssembly().GetName().Version;

4. How would you Read settings from app.config or


web.config in C#?

1 ConfigurationManager.AppSettings["MySetting"]

You will need to add a reference to System.Configuration in your project’s


references folder.

5. When you create and compile an application in


C#, what all are the files get generated in Debug
folder?
When you will create and compile a program in C#, you will see below files in Debug
folder.
– exe – the ‘normal’ executable
– vshost.exe – a special version of the executable to aid debuging; see MSDN for
details
– pdb – the Program Data Base with debug symbols
– vshost.exe.manifest – a kind of configuration file containing mostly dependencies
on libraries

6. Can you add extension methods to an existing


static class?
No. Extension methods require an instance of an object. However, you can do
something like this:

1 public static class Extensions

2 {

3 public static T Create<T>(this T @this)

4 where T : class, new()


5 {

6 return Utility<T>.Create();

7 }

8 }

10 public static class Utility<T>

11 where T : class, new()

12 {

13 static Utility()

14 {

15 Create =

16 Expression.Lambda<Func<T>>(Expression.New(typeof(T).GetConstructor(Type.EmptyTypes))).Compile();

17 }

18 public static Func<T> Create { get; private set; }

7. What is the difference between Object pooling


and Connection pooling in C#?
The object pool implementation will increase the size of the pool up to the specified
maximum. When the maximum is reached,instead of throwing an exception, it
makes the client wait until an object is returned to the pool, and then gives the
newly returned object to the waiting client.

The connection pool implementation does not have a maximum size parameter – it
will keep creating new connections to meet demand (eventually it will hit some
system limit and the request will fail in some way that isn’t specified.

8. What is the use of volatile keyword?


The volatile keyword indicates that a field might be modified by multiple threads
that are executing at the same time. Fields that are declared volatile are not
subject to compiler optimizations that assume access by a single thread. This
ensures that the most up-to-date value is present in the field at all times.
The volatile modifier is usually used for a field that is accessed by multiple threads
without using the lock statement to serialize access.
The volatile keyword can be applied to fields of these types:
– Reference types.
– Pointer types (in an unsafe context). Note that although the pointer itself can be
volatile, the object that it points to cannot. In other words, you cannot declare a
“pointer to volatile.”
– Integral types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
– An enum type with an integral base type.
– Generic type parameters known to be reference types.
– IntPtr and UIntPtr.

9. What is the use of Partial class in C#?

– By Using Partial Classes, multiple developer can work on the same class easily.
– Partial classes are mainly used by code generator to keep different concerns
separate
– you can also define Partial methods as well where a developer can simply define
the method and the other developer can implement that.

10. What is an async method in C#?


An async method is a method that returns to the calling method before completing
all its work, and then completes its work while the calling method continues its
execution.
An async method has the following characteristics:

– An async method must have the async keyword in its method header, and it must
be before the return type.
– This modifier doesn’t do anything more than signal that the method contains one or
more await expressions.
– It contains one or more await expressions. These expressions represent tasks that
can be done asynchronously.
– It must have one of the following three return types.
− void :If the calling method just wants the async method to execute, but doesn’t
need any further interaction with it
− Task : If the calling method doesn’t need a return value from the async method,
but needs to be able to check on the async method’s state
− Task :If the calling method is to receive a value of type T back from the call, the
return type of the async method must be Task
– An async method can have any number of formal parameters of any types but it
cannot be out or ref parameters.
– The name of an async method should end with the suffix Async.
– Otherthan Methods, lambda expressions and anonymous methods can also act as
async objects.
What is the use of private constructor in C#?
A private constructor is a special instance constructor. It is generally used in classes
that contain static members only. If a class has one or more private constructors and
no public constructors, other classes (except nested classes) cannot create instances
of this class.

1 public class Counter

2 {

3 private Counter() { }

4 public static int currentCount;

5 public static int IncrementCount()

6 {

7 return ++currentCount;

8 }

9 }

10

11 class TestCounter

12 {

13 static void Main()

14 {

15 // If you uncomment the following statement, it will generate

16 // an error because the constructor is inaccessible:

17 // Counter aCounter = new Counter(); // Error

18

19 Counter.currentCount = 10;

20 Counter.IncrementCount();

21 Console.WriteLine("New count: {0}", Counter.currentCount);

22

23 // Keep the console window open in debug mode.

24 Console.WriteLine("Press any key to exit.");


25 Console.ReadKey();

26 }

27 }

What is the use of static constructor in C#?


Static constructor is a special constructor that gets called before the first object of
the class is created. It is used to initialize any static data, or to perform a particular
action that needs performed once only.
The time of execution of static constructor is not known but it is definitely before
the first object creation – may be at the time of loading assembly.

1 //Example1

2 using System;

3 public Class Student

4 {

5 static Student()

6 {

7 // initialize static members only.

8 }

9 // other methods here.

10 }

11 // Example2

12 using System;

13 public class MyStaticClass

14 {

15 static int count;

16 static MyStaticClass()

17 {

18 count = 0;

19 Console.WriteLine("Static class is initialized");


20 }

21 public static void MyMethod(string name)

22 {

23 Console.WriteLine("Static class is initialized " + name);

24 }

25 }

26 MyStaticClass.MyMethod("Steve") ; //method call

27 //constructor will be called automatically

28

29 Output:

30 Static class is initialized Steve

What is Constructor chaining in C#?


When you want to share initialization code among multiple constructors, you can do
it using constructor chaining.In Constructor chaining,the constructor calls another
constructor in its class using the this().

1 public Test( bool a, int b, string c )

2 : this( a, b )

3 {

4 this.m_C = c;

5 }

6 public Test( bool a, int b, float d )

7 : this( a, b )

8 {

9 this.m_D = d;

10 }

11 private Test( bool a, int b )

12 {
13 this.m_A = a;

14 this.m_B = b;

15 }

Does C# provide Copy Constructor for an object?


C# doesn’t provide a copy constructor for objects, but you can write one yourself.

1 class Employee

2 {

3 // Copy constructor.

4 public Employee(Employee previousEmployee)

5 {

6 Name = previousEmployee.Name;

7 Age = previousEmployee.Age;

8 }

10 //// Alternate copy constructor calls the instance constructor.

11 //public Employee(Employee previousEmployee)

12 // : this(previousEmployee.Name, previousEmployee.Age)

13 //{

14 //}

15

16 // Instance constructor.

17 public Employee(string name, int age)

18 {

19 Name = name;

20 Age = age;

21 }
22

23 public int Age { get; set; }

24

25 public string Name { get; set; }

26

27 public string Details()

28 {

29 return Name + " is " + Age.ToString();

30 }

31 }

32

33 class TestEmployee

34 {

35 static void Main()

36 {

37 // Create a Employee object by using the instance constructor.

38 Employee Employee1 = new Employee("George", 40);

39

40 // Create another Person object, copying person1.

41 Employee Employee2 = new Employee(Employee1);

42

43 // Change each person's age.

44 Employee1.Age = 39;

45 Employee2.Age = 41;

46

47 // Change Employee2's name.

48 Employee2.Name = "Charles";

49

50 // Show details to verify that the name and age fields are distinct.
51 Console.WriteLine(Employee1.Details());

52 Console.WriteLine(Employee2.Details());

53

54 // Keep the console window open in debug mode.

55 Console.WriteLine("Press any key to exit.");

56 Console.ReadKey();

57 }

58 }

59 // Output:

60 // George is 39

61 // Charles is 41

What is Parameterized Constructor in C#?

1 Class Student

2 {

3 int roll;

4 float marks;

5 public Student(int a, float b)//constructor

6 {

7 roll = a;

8 marks = b;

9 }

10 //other members

11 }

The above defined constructor takes two arguments one int and other float to
initialize instance members roll and marks for the newly created object and
therefore it is called parameterized constructor. With this type of constructor, the
object will be created as follows :

1 Student obj = new Student( 17 , 58.08F);

What is Constructor Overloading in C# and how is it


different than Method Overloading?
A Constructor can be overloaded in C#. Overloaded constructors are differentiated
on the basis of their type of parameters or number of parameters. Constructor
overloading is not much different than method overloading. In case of method
overloading you have multiple methods with same name but different signature,
whereas in Constructor overloading you have multiple constructor with different
signature but only difference is that Constructor doesn’t have return type in C#.

1 using System;

2 public Class OverloadStudent

3 {

4 public OverloadStudent ()

5 {

6 //Default constructor

7 }

8 public OverloadStudent (int age)

9 {

10 //Single parameter constructor

11 }

12 public OverloadStudent (int age, string name)

13 {

14 //two parameter constructor

15 }

16 }
Now, following are the ways through which we can instantiate the object.

1 OverloadStudent obj=new OverloadStudent() ; //Default constructor will get called

2 OverloadStudent obj=new OverloadStudent(43) ; //Single parameter constructor will get called

3 OverloadStudent obj=new OverloadStudent(47,"Steve") ; //Two parameters constructor will get called

Can you create an object without using new


operator in C#?
Yes, You can create object in C# without using new operator.

i. Using newInstance() method:

1 // A constructor with two arguments:

2 public product(int x, int y)

3{

4 this.x = x;

5 this.y = y;

6}

1 product p1 = new product();

2 product p2 = new product(5, 3);

ii. Using Clone() method:

1 myClass a = new myClass();

2 myClass b = (myClass)a.Clone();
Can we Overload main() method in C#?
Yes, We can overload main() method. A C# class can have any number of main()
methods.
But to run the C# class, class should have main() method with signature as “public
static void main(String[] args)”. If you do any modification to this signature,
compilation will be successful. But, You will get run time error as main method not
found.

1 public class MainMethod

2 {

3 public static void Main(string[] args)

4 {

5 Console.WriteLine("Hello World !!");

7 }

8 void Main(int args)

9 {

10 Console.WriteLine("First main method executed !!");

11 }

12

13 double Main(int i, double d)

14 {

15 Console.WriteLine("Second main method executed !!");

16

17 return d;

18 }

19 }

Can we declare main() method as private in C#?


Yes. You can mark the main() method as public,private or protected. If you want to
initiate entry point by any external program,then you might need to make it public
so it is accessible. You can mark it as Private if you know there is no external usage
for the application then it is better to make it private so no external application
access it.

1 public class MainMethod

2 {

3 private static void Main(string[] args)

4 {

5 Console.WriteLine("Hello World !!");

7 }

9 }

Can We Declare main() Method As Non-Static in C#?


No, If you will declare the main method as non static keyword then you will get a
runtime error.”the program does not contain a static ‘Main’ method suitable for an
entry point”.

1 public class MainMethod

2 {

3 public void Main(string[] args)

4 {

5 Console.WriteLine("Hello World !!");

7 }

9 }

Can we change return type of main() method in C#?


Yes, we can. From the msdn (https://msdn.microsoft.com/en-
us/library/0fwzzxz2.aspx): “If the return value from Main is not used, returning void
allows for slightly simpler code. However, returning an integer enables the program
to communicate status information to other programs or scripts that invoke the
executable file. The following example shows how the return value from Main can be
accessed.”

1 public class MainMethod

2 {

3 public static int Main()

4 {

5 return 100;

6 }

8 }

Can main() method take an argument other than


string array?
No. The parameter of the Main method is a String array that represents the
command-line arguments.Command line arguments commonly get used when you
need to pass information to your application at runtime. If you don’t have any
parameter to pass then:

1 public class MainMethod

2 {

3 public static void Main()

4 {

5 Console.WriteLine("Hello World !!");

6 }

8 }

Can we run C# class without main() method?


No. The Main method is the entry point of a C# console application or windows
application. (Libraries and services do not require a Main method as an entry point.)
When the application is started, the Main method is the first method that is invoked.

There can only be one entry point in a C# program. If you have more than one class
that has a Main method, you must compile your program with the /main compiler
option to specify which Main method to use as the entry point.
1. What is Dynamic Language Runtime?
o DLR is a runtime environment that adds a set of services for dynamic
languages to the CLR
o DLR makes it easier to develop dynamic languages to run on .net framework
and give them .net interoperability
o DLR introduces dynamic objects in C#
o DLR helps you create libraries that support dynamic operations
o Examples of languages developed by using DLR is IronPython,IronRuby etc

2. What all are the advanges of DLR?


DLR provides following advantages.

o Simplifies porting Dynamic Languages to the .NET Framework


o DLR allows language implementers to avoid creating lexical
analyzers,parsers,semantic analyzers,code generators etc.
o To use DLR, a language needs to produce expression trees that
implement the IDynamicMetaObjectProvider Interface.Expression trees
are nothing but language level code in tree like structure. you will
learn more on expression trees in below link.
o http://www.csharpstar.com/expression-trees-in-csharp/
o Enables dynamic features in Statically Typed Languages
o Existing .net framework laguage like C# can create dynamic objects and
use them together with statically typed objects
o Provides future benefits of the DLR and .net framework
o If the .net framework releases a new version that has faster assembly
loading time then the languages implemented by DLR immediatelt get
the same benefit.
o Enables sharing of Libraries and Objects
o The objects and libraries implemented in one language can be used by
other language
o Provides fast Dynamic Dispatch and Invocation
o DLR creates rules for binding operations by supporting advanced
polymorphic caching

3. What is Dynamic Language and what all are the


advanges of Dynamic Language?
Dynamic languages like Javascript,PHP,Ruby etc.. can identify the type of an object
in runtime but in statically typed languages like C# you must design object in design
time.

Advantages:
o The ability to use a rapid feedback loop (Read-Evaluate-Print loop). This lets
you enter several statements and immediately execute them to see the
results
o Supports both top-down and buttom-up development
o When you use top-down approach, you can call functions that are not yet
implemented and add underlying implementation when you need them
o Easier refactoring and code modification

4. Explain the Architecture of DLR ?


The following diagram shows the architecture of dynamic language runtime.

The DLR adds a set of services to the CLR for better supporting dynamic languages.
These services include the following:

o Expression trees:
o The DLR uses expression trees to represent language semantics. For this
purpose, the DLR has extended LINQ expression trees to include control
flow, assignment, and other language-modeling nodes.
o Call site caching:
o A dynamic call site is a place in the code where you perform an
operation like a + b or a.b() on dynamic objects. The DLR caches the
characteristics of a and b (usually the types of these objects) and
information about the operation. If such an operation has been
performed previously, the DLR retrieves all the necessary information
from the cache for fast dispatch.
o Dynamic object interoperability
o The DLR provides a set of classes and interfaces that represent dynamic
objects and operations and can be used by language implementers and
authors of dynamic libraries. These classes and interfaces
include IDynamicMetaObjectProvider, DynamicMetaObject, DynamicOb
ject, and ExpandoObject.

The DLR uses binders in call sites to communicate not only with the .NET
Framework, but with other infrastructures and services, including Silverlight and
COM. Binders encapsulate a language’s semantics and specify how to perform
operations in a call site by using expression trees. This enables dynamic and
statically.

5.What are the Binders and What all are the binders
supported by .net framework?
The DLR uses binders in call sites to communicate not only with the .NET
Framework, but with other infrastructures and services, including Silverlight and
COM. Binders encapsulate a language’s semantics and specify how to perform
operations in a call site by using expression trees. This enables dynamic and
statically.

.net supports following binders:


1.Object Binder – Enables to communicate with .net objects
2.JavaScript Binder – Enables to communicate with JavaScript
3. Python Binder – Enables to communicate with IronPython
4. COM Binder – Enables to communicate with COM
5. Ruby Binder – Enables to communicate with IronRuby

6. What all are the different services provided by


DLR to CLR?
The DLR adds a set of services to the CLR for better supporting dynamic languages.
These services include the following:
o Expression trees:
o The DLR uses expression trees to represent language semantics. For this
purpose, the DLR has extended LINQ expression trees to include control
flow, assignment, and other language-modeling nodes.
o Call site caching:
o A dynamic call site is a place in the code where you perform an
operation like a + b or a.b() on dynamic objects. The DLR caches the
characteristics of a and b (usually the types of these objects) and
information about the operation. If such an operation has been
performed previously, the DLR retrieves all the necessary information
from the cache for fast dispatch.
o Dynamic object interoperability
o The DLR provides a set of classes and interfaces that represent dynamic
objects and operations and can be used by language implementers and
authors of dynamic libraries. These classes and interfaces
include IDynamicMetaObjectProvider, DynamicMetaObject, DynamicOb
ject, and ExpandoObject.

7. What is Dynamic data types?


Dynamic data types is a reference data type which is checked at runtime instead of
compile time and allows you to detect error in runtime only.

8. What is the difference between dynamic and var


data types?
9. Which class is used for converting Data types?
The System.Convert class provides set of methods for converting data types.

10. Explain Expando object and Dynamic Object


classes ?
The Expando object class refers to a class whose members can be explicitly added
and removed at runtime but the Dynamic object class enables to define the dynamic
behavior for an object at runtime.

The DynamicObject class cannot be instantiated directly.So to implement Dynamic


behavior, you must inherit from the DynamicObject class and override necessary
methods.
1. What is Object Oriented Programming?
OOP is a technique to develop logical modules, such as classes that contains
properties, fields and events. OOP provides many concepts such as inheritance, data
binding, polymorphism etc.

Object means a real word entity such as pen,paper, chair, table etc.

Object-Oriented Programming is a methodology or paradigm to design a program


using classes and objects.

It simplifies the software development and maintenance by providing some


concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Simula is considered as the first object-oriented programming language.

2. What is a class?
A class can be defined as the primary building block of OOP. A class contains data
and behavior of an entity.

A class in C# can contain:

1. data member
2. properties
3. constructor
4. methods

Notes:

1. Class name should start with uppercase letter and be a noun e.g. String, Color,
Button, System, Thread etc.
2. The name of the constructor is always same as the class name
3. A class can have any number of data members, properties, constructors and
methods
4. Data member defined using a class is called as object reference.
5. A class can have a data member which is an object reference of the same class
Like the manager of the employee is also a employee.
3. What is an Object?
An entity that has state and behavior is known as an object e.g. pen, table, car etc.
It can be physical or logical.

An object has three characteristics:

o state: represents data (value) of an object.


o behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
o identity: Object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. But,it is used internally by the
compiler to identify each object uniquely.

For Example: Pen is an object. Its name is Parker, color is black etc. known as its
state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects
are created. So object is the instance(result) of a class. For example, you have a
class called Vehicle and car is the object of that class.

4. Explain the basic features of OOPs ?


OOPs has four basic features.

o Abstraction : Abstraction is the process of exposing only the relevant data to


the users without showing unnecessary information
o Polymorphism : I allows you to use an entity in multiple forms
o Encapsulation : Prevents the data from unwanted access by binding of code
and data in a single unit called object
o Inheritance : Promotes the reusability of code and eliminates the use of
redundant code.

5. What are Abstract classes ?


An abstract class is a class that can not be instantiated and is always used as a base
class.

Characteristics of an abstract class:

o You can not instantiate an abstract class directly


o You can have abstract as well as non abstract members in an abstract class
o You must declare one abstract method in the abstract class
o An abstract class is always public
o An abstract class is declared using abstract keyword
6. Explain the features of an Interface
o An Interface contains only the signature of methods
o An Interface has no Implementation on its own
o An Interface is used to implement multiple inheritance in code.
o It defines a static set of methods and their arguments
o Variables in Interface must be declared as public,static and final
o Methods in an Interface must be declared as public and abstract
o A class implementing an Interface must implement all of its method
o An Interface can derive from more than one Interface

7. Difference between an abstract class and an


Interface ?

8. Explain different types of Inheritance


There are four types of Inheritance in Object oriented programming.

o Single Inheritance : contains one base class and one derived class
o Hierarchical Inheritance : Contains one base class and multiple derived
classes of same base class
o Multilevel Inheritance : Contains a class derived from a derived class
o Multiple Inheritance : Contains several base class and a derived class

9. What is Constructor?
C# constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
A constructor is a special method that is used to initialize an object. Every class has
a constructor,if we don’t explicitly declare a constructor for any C# class the
compiler builds a default constructor for that class. A constructor does not have any
return type. Constructors are responsible for object initialization and memory
allocation of its class.

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

You can read more on constructor here.

10. What is Destructor?


A Destructor is automatically invoked when an object is finally destroyed. The name
of the Destructor is same as class and prefixed with a tilde (~)

A Destructor is used to free the dynamic allocated memory and release the
resources. You can Implement a custom method that allows to control object
destruction by calling the destructor.

o Destructors don not have any return type


o Destructors are always public
o Destructors can not be overloaded

11. What is a Static Constructor?


Static constructor is used to initialize static data of a class. Compiler calls the static
constructor before the first instance is created.

o No access specifier is required to define it


o You can not pass parameters to static constructor
o A class can have only one static constructor
o It can access only static members of class
o It is invoked only once, when the program execution begins

12. What is Method Overloading?


Method Overloading lets you have 2 methods with same name and different
signature.
Overloading can be achieved:
-By changing the number of parameters used.
-By changing the order of parameters.
-By using different data types for the parameters.

13. What is Access Specifier?


An access specifier defines the scope and visibility of a class member. C# supports
the following access specifiers:

o Public
o Private
o Protected
o Internal
o Protected internal

14. What is Encapsulation?


o Encapsulation is a process of hiding the members from outside of class and
implemented using access specifiers
o Encapsulation is also called as information hiding.
o Encapsulation provides a way to preserve the integrity of state data. Rather
than defining public fields, private data fields should be defined.
o Well-encapsulated class should hide its data and the details of how it
operates on data from the outside world. This is termed black box
programming.
o Using this,implementation of the method can be changed by the class author
without breaking any existing code making use of it.

15. What is the difference between Method


Overloading and Method Overriding?

Example:

1 public class Methodoverloading

2 {
3 public int addition(int a, int b) //Two int parameters with same method

4 {

5 return a + b;

6 }

7 public int addition(int a, int b,int c) //Three int Parameters with same method

8 {

9 return a + b + c;

10 }

11 public float addition(float a, float b,float c,float d) //four float type Parameters with same method same as above two

method
12

{
13

return a + b + c + d;
14

}
15

Example:

1 Public class test

2 {

3 public virtual int addition()

4 {

5 return 10;

6 }

7 }
8 public class Amount:test

9 {

10 public override int balance()

11 {

12 return 500;

13 }

14 }

16. What is the difference between Abstraction and


Encapsulation ?
Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used
for hide the code and data in a single unit to protect the data from the outside the
world. Class is the best example of encapsulation. Abstraction refers to showing only
the necessary details to the intended user.

17. What is Operator Overloading ?


Operator overloading is a technique by which operators used in a programming
language are implemented in user-defined types with customized logic that is based
on the types of arguments passed.

Operator overloading facilitates the specification of user-defined implementation for


operations wherein one or both operands are of user-defined class or structure type.
This helps user-defined types to behave much like the fundamental primitive data
types. Operator overloading is helpful in cases where the operators used for certain
types provide semantics related to the domain context and syntactic support as
found in the programming language. It is used for syntactical convenience,
readability and maintainability

18. What is a Delegate ?


Delegates are type safe function pointer. It holds reference to a function.

The signature of delegates matches the signature of the function that it points to
else you will get compilation error.
Delegates are typesafe pointers because it points to a function and holds the
signature of the function.

19. What is multicast Delegate ?


A multicast delegate is a delegate that has references to more than one
function.When you inoke a multicase delegate,all the functions the delegate is
pointing to are also invoked.

There are 2 ways to create multicast delegate.

+ or += to register a method with the delegate


– or -= to unregister a method with the delegate
A multicast delegate invokes the methods in invocation list in same order in which
they are added.

20. What are Events ?


Events are user actions such as key press, clicks, mouse moves, etc., or some
occurrence such as system generated notifications. Applications need to respond to
events when they occur.

21. What is the difference between Array and


Collection?

Array Collection

The size of a collection can be adjusted dynamically


You need to specify the size of an array at the time

of its declaration.It can not be resized. as per users requirement.It does not have fixed size

The member of an array should be of the same data

type Collection can have elements of different types

22. What is the difference between Shadowing and


Overriding?
Shadowing:

1.You can shadow a base class member in the derived class by using the keyword
New.
2.The method signature, access level and return type of the shadowed member can
be completely different than the base class member.
3.A method or function of the base class is available to the child (derived) class
without the use of the “overriding” keyword.
4.The compiler hides the function or method of the base class. This concept is
known as shadowing or method hiding.
5.In the shadowing or method hiding, the child (derived) class has its own function,
the same function is also available in the base class.

Overriding:

1.Method overriding is an important feature of OOPS that allows us to re-write a


base class function or method with a different definition.
2.Overriding is also known as “Dynamic Polymorphism” because overriding is
resolved at runtime.
3.The method signature, access level and return type of the hidden member has to
be same as the base class member
4.In other words both methods (base class method and derived class method) have
the same name, same number and same type of parameter in the same order with
the same return type.
5.The overridden base method must be virtual, abstract or override.

You can look at C# implementation on Shadowing and Overriding here.

23. What is the difference between Class and


Structure?

Class Structure

A Class is a reference type A Structure is a value type

By default, the members of a Class are private By default, the members of a Structure are public

Class supports Inheritance Structure does not support Inheritance

Class can contain constructor/destructor Structure does not require Constructor/Destructor


Variables of a Class can be assigned as null Structure members can not have null values

24. What is the similarities between Class and


Structure?
o Access specifiers are identically used in structure and classes to restrict the
access of their data and methods outside their body
o Both can have constructors,methods, properties,fields, constants etc..
o Both can implement Interfaces to use multiple-inheritance in code
o Both can have Delegates and Events

25. What is Enum?


o An enum is a distinct value typewith a set of named constants
o It is declared by using keyword Enum
o Every Enum type has an underlying type which can be any integral type
except char. The default underlying type is int.
o The first enumerator has the value 0 by default and the value of each
successive enumerator is increased by 1
o Enumeration bridge the gap between numbers and objects

26. What is a Nested Class?


Nested class is nothing but defining a class within another class.

Nested classes has the ability to specify private as an access modifier for the class
itself.The use of the private access modifier defines the intended accessibility of the
class and prevents access from outside the class.

27. What is an Indexer?


An Indexer is a member that enables an object to be indexed like Arrays.

28. What is Sealed keyword in C#?


You can disable inheritance by using the sealed keyword on a class or a method.
When used on a class, you can’t derive other classes from it. When used on a
method, derived classes can’t override the method.

29. What is a hashtable?


Hashtable is store multiple items and each of these items is associated with unique
string key. Each item can be accessed using the key associated with it.

30. What is Polymorphism and explain different


types of Polymrphism?
The word polymorphism means having many forms.
polymorphism is ‘one interface, multiple functions’. Polymorphism can be static or
dynamic.

Static Polymrphism:

The mechanism of linking a function with an object during compile time is called
early binding. It is also called static binding. C# provides two techniques to
implement static polymorphism. They are:

1.Function overloading
2.Operator overloading

Dynamic Polymorphism:

The mechanism of linking method to an object during run time is called late
binding.It is also known as run-time polymorphism. Method overriding helps to
implement Dynamic Polymorphism.
ASP.NET

1.What is the Postback in ASP.NET?


A postback is a request sent from a client to server from the same page, user is
already working with.

o Add a new ASP.NET web form page to a project e.g. WebForm1.aspx.


o View the page code in HTML Source view.
o Look the form line of code.

<form id=”form1″ runat=”server”>;


It represents a server-side implementation of form control.

o Now just run the application to see WebForm1.aspx page and view its source
code. HTML source of the page will display form element as follows:
<code>form id="form1" action="WebForm1.aspx"
method="post"&gt;
o You can see that an HTML form element generated with an HTTP method as
“POST” and action=”WebForm1.aspx”. So, if a submit button is clicked, the
page will postback to itself by default.
o Following figure will also give you more understanding on ASP.NET Postback.

You can read more on postback vs Callback difference here.

2. Difference between ASP.NET WebForms and ASP.NET


MVC?
ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In
this approach, every page has it’s own controller i.e. code-behind file that processes
the request. On the other hand, ASP.NET MVC uses Front Controller approach. In this
approach a common controller for all pages, processes the requests.
3.Please briefly explain ASP.NET Page life Cycle?
Initialization: Controls raise their Init event in this stage.Objects and variables are
initializes for complete lifecycle of request.
LoadViewState: is a post back stage and loads the view state for the controls that
enabled its view state property.

LoadPostBackData: is also a post back stage and loads the data posted for the
controls and update them.
Load: In this stage page as well as all the controls raise their Load event. Till this
stage all the controls are initialized and loaded. In most of the cases, we are coding
this event handler.
RaisePostBackEvent: is again a postback stage. For example, it’s raise against a
button click event. We can easily put our code here to perform certain actions.
SaveViewState: Finally, controls state is saved in this stage before Rendering HTML.
Render: This is the stage where HTML is generated for the page.
Dispose: Lastly, all objects associated with the request are cleaned up.

You can see the detailed explanation on ASP.net page life cycle here

4.What is the difference between custom controls and


user controls?
Custom controls are basically compiled code i.e. DLLs. These can be easily added to
toolbox, so it can be easily used across multiple projects using drag and drop
approach. These controls are comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to
create but tightly couple with respect to User Interface and code. In order to use
across multiple projects, we need to copy and paste to the other project as well.

5.Please briefly explain the usage of Global.asax?


Global.asax is basically ASP.NET Application file. It’s a place to write code for
Application-level events such as Application start, Application end, Session start and
end, Application error etc. raised by ASP.NET or by HTTP Modules.

There is a good list of events that are fired but following are few of the important
events in Global.asax:

o Application_Init occurs in case of application initialization for the very first


time.
o Application_Start fires on application start.
o Session_Start fires when a new user session starts
o Application_Error occurs in case of an unhandled exception generated from
application.
o Session_End fires when user session ends.
o Application_End fires when application ends or time out.

You can read the detailed article here.

6.What is the concept of view state in ASP.NET?


o ViewState of a webform is available only within that webform
o ViewState is stored on the page in a hidden field called viewState. it will be
lost if the user will navigate away from the page or if browser is closed
o ViewState is used y all asp.net controls to retain their state across postback

You can read the difference between view state,session state and Application
state here.

7.Difference between Response.Redirect and


Server.Transfer?
Both Server.Transfer and Response.Redirect are ASP.NET objects and are used for
navigation between web-pages. However, there are noticeable differences between
these two techniques:
Response.Redirect()
o Response.Redirect() redirects the user to another web-page which may or
may not be on thesame server. It can redirect the user to an external website
on a different server.
o Response.Redirect() updates the address bar and adds the updated URL to the
browser history. User can click back on the browser to navigate to the
previous page.
o Response.Redirect() terminates the request with HTTP 302 status and client-
side roundtrip. Client then navigates to the new address and the browser
address bar and history updates. The client pays the cost of additional round-
trips to the server on each request.
o Form variables are are not transferred upon a call to Response.Redirect().
Server.Transfer()
o Server.Transfer() quits current execution of the web-page and redirects the
user to another web-page on thesame server. It cannot send the user to an
external website on a different server.
o Server.Transfer() keeps the URL unchanged in the address bar. It happens
entirely on the server side and the client browser’s address bar remains
constant. User cannot click on back button on the browser to navigate to the
previous page
o Server.Transfer() reduces the server request and conserves server resources.
It simply changes the focus on the Web Server and transfers the request. With
Server.Transfer() there are less number of HTTP requests, which eases
pressure on the Web Server and makes the application execute faster.
o Developer can transfer Query Strings and form variables with a little bug-
bashing. The Server.Transfer() method has a second parameter
– preserveForm. If this is set to True, the existing query string and form
variables will be available to the transferred page. Ex –
Server.Transfer(“webpage2”, True);
8.What are the different types of Validation controls in
ASP.NET?
In order to validate user input, ASP.NET provides validation server controls. All
validation controls inherits from BaseValidator class which contains the common
validation properties and methods like ControlToValidate, Enabled, IsValid,
EnableClientScript, ValidationGroup,Validate() etc.

ASP.Net provides a range of validation controls:

o RequiredFieldValidator validates required input.


o RangeValidator validates the range. Validates that input is between the given
range values.
o CompareValidator validates or compares the input of a control with another
control value or with a fixed value.
o RegularExpressionValidator validates input value against a defined regular
expression pattern.
o CustomValidator allows to customize the validation logic with respect to our
application logic.
o ValidationSummary displays all errors on page collectively.

9.What are HttpHandlers and HttpModules in ASP.NET?


HttpHandler: ASP.NET Engine uses HttpHandlers to handle specific requests on the
basis of it’s extensions. ASP.NET Page Handler handles all requests coming for
(.aspx) pages. We can define our own custom HttpHandler to handle a specific
request with a specific extension, say .jpeg, .gif, or .ahmad. But there will always
be only one handler for a specific request.

HttpModule: ASP.NET Engine uses HttpModules to inject some specific functionality


along with ASP.NET default functionality for all incoming requests regardless of its
extensions. There are a number of built-in modules already available in ASP.NET
HTTP Pipeline. But we can write our own custom HTTP module to perform some
additional functionality (for example, URL rewriting or implementing some security
mechanism) for all incoming requests.
We have discussed HttpHandler and HttpModule in detailed here.

10.What are the types of Authentication in ASP.NET?


There are three types of authentication available in ASP.NET:
o Windows Authentication: This authentication method uses built-in windows
security features to authenticate user.
o Forms Authentication: authenticate against a customized list of users or
users in a database.
o Passport Authentication: validates against Microsoft Passport service which is
basically a centralized authentication service.

11.What are Session state modes in ASP.NET?


ASP.NET supports different session state storage options:

o In-Process is the default approach. It stores session state locally on same web
server memory where the application is running.
o StateServer mode stores session state in a process other than the one where
application is running. Naturally, it has added advantages that session state is
accessible from multiple web servers in a Web Farm and also session state
will remain preserved even web application is restarted.
o SQLServer mode stores session state in SQL Server database. It has the same
advantages as that of StateServer.
o Custom modes allows to define our custom storage provider.
o Off mode disables session storage.

12.Hyperlink Vs LinkButton in ASP.NET?


A Hyperlink redirects to a given URL identified by “NavigateURL” property but a
LinkButton which actually displays a Hyperlink style button causes a postback to the
same page but it doesn’t redirect to a given URL.

13.Globalization Vs Localization
When we need to build an application that work for multiple cultures e.g en-US, ar-
SAetc, this process of designing and building applications that work for more than
one cultures is called globalization. However, customizing an application for a
specific culture is localization. Both globalization and localization normally go
together.
14. How to access information about a user’s locale in
ASP.NET?
User’s locale information can be accessed
through System.Web.UI.Page.Culture property.

15.Cache Management in ASP.NET?


ASP.NET provided support for Cache Management in almost all versions. In .NET
Framework 3.5 and older, the support for caching was provided through classes
available in System.Web.Caching. But this support was limited
to System.Web meaning for ASP.NET Web Applications only. Now, with .NET
Framework 4.0 and later, this support is enhance to non-Web Applications also by
providing APIs in System.Runtime.Caching.

o ASP.NET supports three types of Caching:


o Page Output Caching
o Partial Page Caching
o Data Caching

16.Difference between Culture and UICulture


properties in ASP.NET?
CultureInfo class plays an important role for localizing our application pages. Culture
is specific in localizing non-visual parts of the page like DateTime, Currency, number
formatting etc.

while UICulture is specific in localizing visual part of a webpage like Language being
used to display the contents of the web page.

17.What is State Management?


HTTP is a stateless protocol by nature. So, we need some mechanism to preserve
state (i.e. state of a webpage, a control or an object etc.) between subsequent
requests to server from one or more clients. and this mechanism is referred as State
Management in ASP.net

You can read more detailed article on state management here.

18.What are the State Management Techniques used in


ASP.NET?
State Management techniques used in ASP.NET can be categorized in two types:

1. Client-Side State Management


o View State
o Control State
o Hidden Fields
o Cookies
o Query String
2. Server-Side State Management
o Application State
o Session State
o Profile Properties
o Cache
You can read more detailed article on state management here.

19.What is ViewState? or Explain ViewState as State


Management Technique?
o ViewState is one of the Client-Side State Management techniques that
provides page-level state management, which means state is preserved
between subsequent requests to same page.
o By using this technique, state of the page along with its controls is stored in a
hidden form field i.e. “__VIEWSTATE” and this field is again available on
server when page is posted back with HTTP Request.
o ViewState data is encoded in Base64 String encoded format.
o ViewState can be enabled or disable at different levels:
o Control Level
o ViewState for a specific control can be enabled or disabled by
setting EnableViewState
o Page Level
o ViewState for a specific control can be enabled or disabled by
setting EnableViewState
o Application Level
For whole application, we can enable/disable views in configuration file.

20.What is the difference between Application and


Session State?
Application state is basically a common data repository for an application’s all users
and their all sessions. On the other hand, Session state is specific to a single user
session. You can read more detailed explanation here.

21.What is the difference between Session.Clear() and


Session.Abandon() in ASP.NET?
Session is a Collection and it stores data as Key/Value pair.

Session.Clear() clears all the session values but doesn’t destroy the Session.

Session.Abandon() destroys the session object.

In otherwords ,Session.Clear() is like deleting all files inside a folder (say “Root”) but
Session.Abandon() means deleting the “Root” folder.

22.Difference between Local and Global resources?


Resources for a localized ASP.NET application can be stored locally as well as
globally.

Local resources are specific to web page and stored in a folder App_LocalResources.

It can be accessible to that specific page only. Global resources are accessed by
almost all application pages and stored in App_GlobalResources folder.

23.What is the difference between Label Control and


Literal Control?
A Label control in ASP.NET renders text inside <span> tags while a Literal Control
renders just the text without any tags.
With Label controls we can easily apply styles using it’s CssClass property, however,
if we don’t want to apply style/formatting, it’s better to go for a Literal control.
24.What is the difference between var and dynamic?
25. Difference between String and StringBuilder?

Serving application data even if the original source is temporarily down, thus
improving availability of an application.
1. What is Caching and what are the pros and cons of
using it?
Caching is a mechanism that improve performance for an application by storing data
in memory for fast access.
When the application will access data from Cache (i.e. in-memory) instead of
fetching it from original data store (may be a database), it will definitely improve
performance.
But Caching benefits are not limited to performance only, it also improve application
Scalability as well as Availability.

o Load on server is reduced when data is fetched from Cache instead of original
source, thus improving scalability of an application.
o Caching normally keep serving application data even if the original source is
temporarily down, thus improving availability of an application.

Advantages:

The advantages of web caching via proxy servers include:

o faster access to valid cached resources


o saving on costly use of bandwidth
o imposing controls on access to dubious material
o collecting useful statistics on web access
o providing cached resources even when origin server is down

Disadvantages:

Disadvantages of web caching include

o slower performance if the resource isn’t found in the cache


o being given a stale copy of a resource when an uptodate copy is needed
o resources sometimes getting mangled/lost on route
o sharing an access point to the web increasing risks to service
o proxy server access logs invading the privacy of users
o proxy intermediary confusing logging and access control by subscription
services

2. Cache Management in ASP.NET?


ASP.NET provided support for Cache Management in almost all versions. In .NET
Framework 3.5 and older, the support for caching was provided through classes
available in System.Web.Caching. But this support was limited to System.Web
meaning for ASP.NET Web Applications only. Now, with .NET Framework 4.0 and
later, this support is enhance to non-Web Applications also by providing APIs in
System.Runtime.Caching.
ASP.NET supports three types of Caching:

o Page Output Caching


o Partial Page Caching
o Data Caching

3. Page Output Cache Vs Partial Page Cache Vs


Application Data Cache in ASP.NET?
Page Output Cache

In case of Page Output Cache, the output of a complete web page is stored in a
cache.
So, when that web page is accessed again, it will be loaded from cache instead of
fetching page data again from data source.

Partial Page Cache

For Partial Page Cache (also known as Page Fragment Cache), a part or fragment of a
web page is stored in Cache as opposed to complete page caching for Page Output
Cache.
For example, caching a user control on a web page that displays product categories
using Page Fragment Cache.

Data Cache

In some scenarios, we may store frequently used objects into cache using ASP.NET
Cache API.
So, later on, that object will be loaded from cache instead of instantiating object
again and fetching data from original source for it.

4. Authentication Vs Authorization?
Authentication and Authorization are two key security related concepts that are
independent but normally go together.

Authentication is a process that verifies the identity of a user. On ther hand,


Authorization is the process of assigning rights/privileges to already authenticated
user.

For example, when a user tries to login a web application. First of all, user identity
is verified that either he/she is valid registered user of application.
If his/her identity validated successfully then appropriate privileges are assigned
accordingly.
Different users may have different privileges on same application, for example,
user1 can only view/read some records while user2 may have privileges for all CRUD
(Create, Read, Update, Delete) operations on same data.

5. What is Protected Configuration in ASP.NET?


While developing an ASP.NET application, we normally store a number of important
sensitive information in our config files like encryption keys, connection strings etc.
Application vulnerability increases if this sensitive information is stored as plane
text.
So Protected Configuration is an ASP.NET feature that enables to encrypt such
sensitive information in configuration files.

6. How to use Page Output Cache in ASP.NET?


Implementing Page Output Cache in ASP.NET is simple. For Page Output Caching, @
OutputCache directive is used on an ASP.NET page as follows:
<%@ OutputCache Duration=”50″ VaryByParam=”None” %>
Duration value is in seconds and it tells the page that how long to cache the
contents?
Now, when we will access the page, it will verify that either it exists in Cache? if
Yes, then verify that is it expired? If not then fetch it from Cache and render
otherwise create a new instance of the page and put it back to Cache.
The other parameter of this directive is “VaryByParam”. If it’s value is specified to
something as follows:
<%@ OutputCache Duration=”50″ VaryByParam=”ProductId” %>
Now, Cache is dependent on the value of this parameter, If the value of parameter
remains same, page will be fetched from Cache otherwise it will be refreshed
again.For in-depth details on Page Output Cache, follow here.

7. How to use Page Fragment or Partial Page Cache in


ASP.NET?
Page Fragment Caching uses the same @ OutputCache directive with VaryByControl
parameter as follows:
<%@ OutputCache Duration=”50″ VaryByParam=”None”
VaryByControl=”ControlName” %>
In this case, Cache is dependent on the value of Control specified in VaryByControl
parameter. For example, content on a page are dependent on the selected values of
a dropdownlist, so, VaryByControl will have the dropdownlist control name as value.

8. How to use Data Cache in ASP.NET?


We have already explained the usage of Data Cache above in this series of ASP.NET
Interview Questions that in particular situations, we need to store objects into
cache. Adding an object to Cache and accessing it from Cache is simple.
We can use “Add” method to add an object to Cache as:

Cache.Add(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); if


1
(Cache[“ProductKey”] == null)

2
Cache.Add(“ProductKey”,

3
objProduct,

4
null,

5
DateTime.Now.AddSeconds(60),

6
Cache.NoSlidingExpiration,

7
CacheItemPriority.High,

8
null);

To retrieve it back:

1 Product objProduct = (Product) Cache[“ProductKey”];

9. What are the available Authentication modes in


ASP.NET?
There are three types of authentication available in ASP.NET:

o Windows Authentication: This authentication method uses built-in windows


security features to authenticate user.
o Forms Authentication: authenticate against a customized list of users or
users in a database.
o Passport Authentication: validates against Microsoft Passport service which is
basically a centralized authentication service.

10. What is the difference between Windows


Authentication and Forms Authentication in ASP.NET?
Windows Authentication is a way to authenticate a user against Windows accounts.
Windows authentication mode is suitable for corporate users in windows
environment.
In case of Forms Authentication, a separate list of users is maintained for
authentication. For example, we can maintain the list in database and authenticate
user against it.
We can set authentication mode in web.config as follows:
<authentication mode=”Forms”>

11. What is Passport Authentication?


Passport authentication is a centralized authentication service provided by Microsoft
that offers a single logon and core profile services for member sites.

Passport benefits users because they do not need to log on to new limited-access
resources or sites

Passport Authentication actually validates against a centralized authentication


service i.e. Microsoft Passport Service. We don’t need to implement our own custom
authentication mechanism if implementing .NET Passport Single Sign-In (SSI) service.

12. Can you briefly explain how Passport Authentication


works?
As discussed above that Passport Authentication is a central service. It just
authenticate (validate the credentials), no authorization (grant or deny access to a
site). So, implementing application will check for the Passport Authentication
Cookie. In case of unavailability of Passport Cookie, user is redirected to passport
Sign-In page. User provides the credentials on Sign-In page, if
validated, Authentication Cookie is stored on client machine and redirected to the
requested page.
13. What are the advantages of using Passport
Authentication?
Advantages of Passport Authentication are:

1. The sign-in, sign-out, and registration pages are centrally hosted rather than
being specific to each individual site.
2. All .NET Passport sign-in and core profile cookies are strongly encrypted.
3. The central .NET Passport servers return encrypted sign-in and profile
information to your site.
4. Members do not need to retype their sign-in name and password when moving
from site to site.
5. Participating Web sites never receive a member’s password. The
authentication cookie is actually a pair of encrypted time stamps asserting
when the member signed in.
6. There is no real-time, server-to-server communication between participating
Web sites and the central .NET Passport servers.
7. All information exchange occurs through the client’s browser using HTTP
redirects, encrypted information on the query string, and cookies.

14. What is Role-based Security?


Authorization is a process of granting privileges or permissions on resources to an
authenticated user. So,
“Role Based Security is a technique we use to implement authorization on the basis
of user’s roles within an organization. It’s more granular approach to grant or
revoke permissions on resources through user’s roles.“

An example of granting or revoking permissions in configuration file using windows


built-in groups as follows:

<authorization >
<allow roles=”MyDomain1Administrators” / > < !– Allow Admin of this domain —
>
<deny users=”*” / > < !– Deny anyone else. — >
</authorization >

15. What are the different Security Controls in


ASP.NET?
ASP.NET provides several security controls which are actually Web Server controls.
You can find those in your Visual Studio Toolbox.

Login Control:
In almost every application we need to take user credentials on a typical login page.
Login control provides the same standard functionality and reduces the effort for
building it from scratch.
LoginName:
After a user successfully logged in to an application, we normally display his/her
username to top right or some other place on the page. Now, this functionality is
provided by LoginName control.
LoginView Control:
LoginView control displays different view for different users. Using
AnonymousTemplate and LoggedInTemplate, different information can be presented
to different users.
LoginStatus Control:
LoginStatus control implies whether a user is authenticated or not. For an
unathenticated user, it displays a link to login page. On the other hand, for
authenticated user, a logout link is displayed.
LoginRecovery Control:
Password recovery is another important functionality simplified through
PasswordRecovery control. It sends an email with login credentials to registered user
email.

16. What is Code-Access Security (CAS)?


Code Access Security (CAS), in the Microsoft .NET framework, is Microsoft’s solution
to prevent untrusted code from performing privileged actions. When the CLR loads
an assembly it will obtain evidence for the assembly and use this to identify
the code group that the assembly belongs to.

It’s .NET CLR’s security system that restrict the code to perform an unwanted task
by applying security policies. Using CAS (Code Access Security), we can restrict what
our code can do? and also what code can call our code?

17. What are the key functions of Code Access Security?


Key functions of Code Access Security are:

o Defines permissions and permission sets that represent the right to access
various system resources.
o Enables code to demand that its callers have specific permissions.
o Enables code to demand that its callers possess a digital signature, thus
allowing only callers from a particular organization or site to call the
protected code.
o Enforces restrictions on code at run time by comparing the granted
permissions of every caller on the call stack to the permissions that callers
must have.

18. What .NET Tool can be used to Enable/Disable CAS?


Code Access Security Tool (Caspol.exe) can be used to turn Code Access Security ON
or OFF as follows:

o caspol -security on
o caspol -security off
We can also list all code groups using following command.
o caspol -listgroups

19. What is Impersonation in ASP.NET?


When using impersonation, ASP.NET applications can execute with the Windows
identity (user account) of the user making the request.
Impersonation is commonly used in applications that rely on Microsoft Internet
Information Services (IIS) to authenticate the user. ASP.NET impersonation is
disabled by default.
For example, if a user ‘user1′ logged in and IIS is setup to run as Network Service. If
‘user1′ call a piece of code on another computer (may be a web service call), the
other computer will see the IIS user instead of ‘user1′. But we can enable
impersonation to allow ‘user1′ to access the web service using its windows identity
instead of Network Service.

20. How to configure Impersonation in ASP.NET?


By default, impersonation is disabled in ASP.NET. Impersonation can be
Enabled/Disabled as follows:

<configuration>
<system.web>
<identity impersonate=”true”/> <! — To disable set impersonate=”false” –>
</system.web>
</configuration>

Impersonate a specific user account as:

<identity impersonate=”true” userName=”user” password=”pwd” />


1.What is Design Pattern?
A design pattern is a general reusable solution to a commonly occurring problem
within a given context in software design. A design pattern is not a finished design
that can be transformed directly into source or machine code. It is a description or
template for how to solve a problem that can be used in many different situations.
Patterns are formalized best practices that the programmer can use to solve
common problems when designing an application or system

2.What all are the advantages of Design Patterns?


Patterns solve software structural and non functional problems.

Structural problems like:


o Abstraction
o Encapsulation
o Data Hiding
o Separation of Concerns
o Separation of Interface and Implementation
o Single point of reference
o Coupling and Cohesion etc..
Non Functional problems like:
o Efficiency
o Reliability
o Interoperability
o Testability
o Reusability etc..

3.What all are the types of Design Patterns?


There are 3 types of Design Pattern.

o Creational Patterns
o This type of pattern address problems of creating an object and
separating it from operations
o Structural Patterns
o This type of pattern address problems of using object oriented constructs
to organize classes and objects
o Behavioral Patterns
o This type of pattern address problems of assigning responsibilities to
classes
4.What is Creational Design Pattern?
In software engineering, creational design patterns are design patterns that deal
with object creation mechanisms, trying to create objects in a manner suitable to
the situation.

In C#, we have 5 types of Design Patterns in Creational Catagory.

o Singleton
o Factory
o Abstract Factory
o Prototype
o Builder

5.What is Structural Design Pattern?


Structural patterns are concerned with how classes and objects are composed to
form larger structures; the class form of the Adapterdesign pattern is an example.

Structural class patterns use inheritance to compose interface or implementations.

Structural Design Patterns are Design Patterns that ease the design by identifying a
simple way to realize relationships between entities.

In C#, We have 7 types of design patterns in Structural Catagory.

o Adapter
o Bridge
o Composite
o Decorator
o Facade
o Flyweight
o Proxy

6.What is Singleton Design Pattern?


o Singleton ensures a class only has one instance.
o Singleton Provides a global point of access to it.

You can see more details on Singleton Design patterns here.


7.What is Factory Design Pattern?
Factory Design patterns:

o Define an Interface for creating an object but let subclasses decide which
class to instantiate
o Lets a class defer instantiation to subclasses

You can see more details on Factory Design patterns here.

8.What is Abstract Factory Design Pattern?


Abstract Factory Design patterns:

o Provides an interface for creating families of related or dependent objects


without specifying their concrete classes.
o Abstract Factory patterns acts a super-factory which creates other factories.
This pattern is also called as Factory of factories

You can see more details on Abstract Factory Design patterns here.

9.What is Prototype Design Pattern?


Prototype Design patterns:

o Prototype pattern specifies the kind of objects to create using a prototypical


instance, and create new objects by copying this prototype.
o It is used to create a duplicate object or clone of the current object to
enhance performance.

You can see more details on Prototype Design patterns here.

10.What is Builder Design Pattern?


Builder Design patterns:

o Separate the construction of a complex object from its representation so that


the same construction process can create different representations.
o In other words,you will have to design the system in such a way that the
client application will simply specify the parameters that should be used to
create the complex object and the builder will take care of building the
complex object.

You can see more details on Builder Factory Design patterns here.

11.What is Adapter Design Pattern?


Adapter Design patterns:

o The adapter pattern is adapting between classes and objects


o This pattern involves a single class called adapter which is responsible for
communication between two independent or incompatible interfaces
o This works like a bridge between two incompatible interfaces

You can see more details on Abstract Design patterns here.

12.What is Bridge Design Pattern?


Bridge Design patterns:

o Bridge Pattern separates abstraction from its implementation, so that both


can be modified Independently
o Bridge Pattern behaves like a bridge between abstraction class and
Implementer class.

You can see more details on Bridge Design patterns here.

13.What is Composite Design Pattern?


Composite Design patterns:

o Composite pattern composes objects in term of a tree structure to represent


part as well as whole hierarchies.
o Composite pattern creates a class contains group of its own objects. This
class provides ways to modify its group of same objects.
o Composite pattern is used when we need to treat a group of objects and a
single object in the same way
You can see more details on Composite Design patterns here.

14.What is Decorator Design Pattern?


Decorator Design patterns:

o Decorator pattern is used to add new functionality to an existing object


without changing its structure.
o Decorators provide a flexible alternative to subclass for extending
functionality.
o This pattern creates a decorator class which wraps the original class and add
new behaviors/operations to an object at run-time.

You can see more details on Decorator Design patterns here.

15.What is Facade Design Pattern?


Facade Design patterns:

o Facade Design Pattern makes a software library easier to use, understand and
test
o Facade Design Pattern make the library more readable
o Facade Design Pattern reduce dependencies of outside code on the inner
workings of a library
o Facade Design Pattern wrap a poorly designed collection of APIs with a single
well-designed API.

You can see more details on Facade Design patterns here.

16.What is Flyweight Design Pattern?


Flyweight Design patterns:

o Flyweight design pattern is an object that minimizes memory use by sharing


as much data as possible with other similar objects
o Flyweight pattern is used to reduce the number of objects created, to
decrease memory and resource usage. As a result it increase performance
o Flyweight design pattern provides a way to use objects in large numbers
when a simple repeated representation would use an unacceptable amount of
memory.
o The flyweight pattern uses the concepts of intrinsic and extrinsic
data.Intrinsic datais held in the properties of the shared flyweight objects.
This information is stateless and generally remains unchanged, if any change
occurs it would be reflected among all of the objects that reference the
flyweight.Extrinsic data is computed on the fly means at runtime and it is
held outside of a flyweight object. Hence it can be stateful.

You can see more details on Flyweight Design patterns here.

17.What is Proxy Design Pattern?


Proxy Design patterns:

o Proxy Design pattern involves a class, called proxy class, which represents
functionality of another class.
o Proxy is a wrapper or agent object that is being called by the client to access
the real serving object behind the scenes.
MVC

1.What is ASP.net MVC or Explain the overview of MVC


(Model-View-Controller)?
MVC (Model-View-Controller) is an software design pattern that decouples various
components of a web application.

By using MVC pattern, we can develop applications that are more flexible to changes
without affecting the other components of our application.

o “Model”, is domain data.


o “View”, is user interface to render domain data.
o “Controller”, translates user actions into appropriate operations performed
on model.

2.Difference between ASP.NET MVC and ASP.NET


WebForms?
ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In
this approach, every page has it’s own controller i.e. code-behind file that processes
the request. On the other hand, ASP.NET MVC uses Front Controller approach. In this
approach a common controller for all pages, processes the requests.
3.What are the Core features of ASP.NET MVC?
Core features of ASP.net MVC framework are:

o Clear separation of application concerns (Presentation and Business Logic).


It reduces complexity that makes it ideal for large scale applications where
multiple teams are working.
o It’s an extensible as well as pluggable framework. We can plug components
and further customize them easily.
o It provides extensive support for URL Routing that helps to make friendly
URLs (means friendly for human as well as Search Engines).
o It supports for Test Driven Development (TDD) approach. In ASP.NET
WebForms, testingsupport is dependent on Web Server but ASP.NET MVC
makes it independent of Web Server,database or any other classes.
o Support for existing ASP.NET features like membership and roles,
authentication and authorization, provider model and caching etc.

4.What all are the advantages of ASP.Net MVC?


The ASP.NET MVC framework offers the following advantages:

o It makes it easier to manage complexity by dividing an application into the


model, the view, and the controller.
o It does not use view state or server-based forms. it gives full control over the
behavior of an application.
o It uses a Front Controller pattern that processes Web application requests
through a single controller.
o It provides better support for test-driven development (TDD).
o It works well for Web applications that are supported by large teams of
developers and Web designers who need a high degree of control over the
application behavior.

5.What is the difference between ViewData, ViewBag


and TempData?

o Both ViewBag and ViewData are used to to communicate between controller


and corresponding view.
o This communication is only for server call, it becomes null if redirect occurs.
o Its a mechanism to maintain state between controller and corresponding
view.
o ViewData is a dictionary object while ViewBag is a dynamic property (a new
C# 4.0 feature).
o ViewData being a dictionary object is accessible using strings as keys and also
requires typecasting for complex types.
o ViewBag doesn’t have typecasting and null checks.
o TempData is a dictionary object that stays for the time of an HTTP Request.
So, Tempdata can be used to maintain data between redirects i.e from one
controller to the other controller.

For more detailed understanding, read this article.

6.What is Routing in ASP.NET MVC?


Routing plays an important role in an ASP.NET MVC Application execution flow.

It maps request URL to a specific controller action using a Routing Table.In order to
describe user’s actions, MVC framework uses friendly URLs against actions instead of
mapping it to physical files as in case of an asp.net Web Form application.

You can read the detailed article on Routing here.

7.What are Action Methods in ASP.NET MVC?


Action methods perform certain operations by interacting with Model and return
output data backto View. Return type of an action method in ASP.NET MVC is called
an action result. ASP.NET MVC framework provides an abstract class named
“ActionResult” which is basically a base classfor all action results. Also, there are
many built-in action result types derived from ActionResultclass like ViewResult,
PartialViewResult, RedirectResult etc. You can read more on controller and Action
methods here.

8.What are Action Filters in ASP.NET MVC?

o Action filters are used when you want to apply some specific logic before or
after action methods.
o You can apply these action filters to a controller or a specific controller
action.
o Action filters are basically custom classes that provide a mean for adding pre-
action or post-action behavior to controller actions.

You can read the more detailed article on Action filter here.

9.Can you explain briefly the Authorize attribute and


its significance in ASP.net MVC?
Traditionally in ASP.NET we achieve these concept by isolating critical modules from
the rest of theapplication, i.e. by segregating ASPX pages in a folder under the
control of a custom web.config file that redirects not-authenticated and
unauthorized users to a custom login page.

Now ASP.NET MVC relieves the pain in attaining the role based security just by a simple
powerful attribute known as Authorize.
In default all the Controllers and Action methods are accessible by both Anonymous
andAuthenticated users.
All the public methods inside the Controllers can be easily accessed if one knows the method
name and the route pattern.

You can read the detailed article on Authorize attribute and its significance here.

10.What is Attribute Routing in ASP.net MVC?


In ASP.NET MVC, we use friendly URLs that are mapped to controller’s actions
instead of physical files as in case of ASP.NET WebForms. Now in ASP.NET MVC5, we
can use attributes to define routes giving better control over the URIs

11.What is Scaffolding in ASP.net MVC and what all are


the advantages of using it?
o Scaffolding is a code generation Framework
o It is developed by Microsoft to perform CRUD(Create, Retrieve,Update and
Delete) operations for us.
o Scaffolding engine uses Microsoft’s T4 templates to generate basic controllers
and views for the models
o Scaffolding blends with Entity Framework and creates the instance for the
mapped entity model and generates code of all CRUD Operations

Advantages:

o RAD approach for data-driven web applications.


o Minimal effort to improve the Views.
o Data Validation based on database schema.
o Easily created filters for foreign key or boolean fields

You can read more on Scaffolding here.

12.What is the difference between ASPX View Engine


and Razor View Engine?
13. What is ASP.net Identity?
ASP.NET Identity Framework is an open source platform and can be customized
according to requirement. Through this platform it provides a user membership in
the form of store or hybrid application which eradicates every security risk to web
applications.ASP.NET Identity Framework 2.0 can be used with ASP.NET Web Forms,
MVC, Web Pages, Web API, and SignalR.

This platform provides the major security like Two Factor Authentication, Account
Lockout, and Account Confirmation etc

You can read the more detailed information on ASP.net Identity here.

14.What are ASP.net MVC HTML Helpers?


HTML Helper in ASP.NET MVC is a method returning a string.The returning string is
basically a HTML string that can render a HTML tag.

HTML helper are comparatively lightweight because they don’t have view state and
event model like Web Form Controls.

Along with the built in HTML helpers, we can also create our own custom helpers to
fulfill our specific needs.

Standard HTML Helpers can be categorized as follows:

o URL Helpers
o HTML Links
o Image Links
o HTML Form Elements

You can read more on HTML Helper here.

15. What is Partial view in ASP.net MVC and what all


are the advantages of it?
o Partial View in ASP.NET MVC serves the same purpose as that of a User
Control in ASP.NETWeb Forms.
o In order to reuse a View in our MVC application (For example, placing a
header, list of items or footer etc.),
o Partial Views are introduced by Microsoft that basically renders inside a
Parent View

Advantages:
using Partial View in ASP.NET MVC has following advantages:

o Enhances reusability by packaging up common website code instead of


repeating the same in different pages.
o Easy to maintain. Changes in future are simple to accommodate.

You can read more on Partial view here.

16. Explain the Dependency Injection in ASP.net MVC?


o Dependency Injection (DI) is a design pattern that takes away the
responsibility of creating dependencies from a class thus resulting in a loosely
coupled system
o The core features of the DI container have been abstracted out to
the IServiceProviderinterface and are available throughout the stack.
Because the IServiceProvider is the same across all components of the
ASP.NET framework a single dependency can be resolved from any part of the
application.
o The DI container supports just 4 modes of operation:
o Instance – a specific instance is given all the time. You are responsible
for its initial creation.
o Transient – a new instance is created every time.
o Singleton – a single instance is created and it acts like a singleton.
o Scoped – a single instance is created inside the current scope. It is
equivalent to Singleton in the current scope.

Advantages of Dependency Injection:

o Reduces class coupling


o Increases code reusing
o Improves code maintainability
o Improves application testing

You can read more detailed explanation with examples on Dependency


Injection here.

18. What is ViewEngine in ASP.net MVC?


View Engine in ASP.NET MVC is used to translate our views to HTML and then render
to response.

Multiple View Engines are available for MVC including ASPX, Razor, NHaml etc.
Normally in ASP.NET MVC, a View Engine translates view into HTML by:

o Providing implementation of IViewEngine (as template provider)


o IView (as rendering template) and
o A Template Engine for parsing and compiling view file into executable code.

ASPX View Engine is also known as Web Form View Engine. it’s syntax as “<%= %>” or
“<%: %>” for rendering server-side contents.

19.What is Bootstrap in MVC5?


o Bootstrap (a front-end framework) is an open source framework that makes
use of HTML,CSS,JavaScript for building responsive web applications.
o Bootstrap provides a base collection including layouts, base CSS, JavaScript
widgets, customizable components and plugins.
o Bootstrap is developed by 2 developers from twitter to accelerate web
development

You can read more detailed article on Bootstrap here.

20.What is ASP.net vNext?


ASP.NET vNеxt соnѕidеrѕ the ASP.net features from very begining till рrеѕеnt dау.It
supports:

o Bеttеr execution
o Lоwеr аѕѕеt utilizаtiоn
o An аѕуnс mоdеl for еnhаnсеd еxесutiоn
o Adaptability
o Eсоnоmу in cloud-based fасilitаting ѕituаtiоnѕ.
HTML5

1.What’s new in HTML 5 DocType and Charset?


Normally for HTML files first line of code is DocType which basically tells browser
about specific version of HTML. HTML5 is now not subset of SGML. As compared to
previous version/standards of HTML, DocType is simplified as follows:
<!doctype html>
And HTML 5 uses UTF-8 encoding as follows:
<meta charset=”UTF-8″>

2.How can we embed Audio in HTML 5?


HTML 5 comes with a standard way of embedding audio files as previously we don’t
have any such support on a web page. Supported audio formats are as follows:

o MP3
o Wav
o Ogg.

Syntax:

<audio controls>
<source src=”testAudio.mp3″ type=”audio/mpeg”>
Your browser does’nt support audio embedding feature.
</audio>
Description:

src value can be relative as well as absolute URL. We can also use
multiple <source> elements pointing to different audio files.

o controls – it adds controls such as volume, play and pause.


o autoplay – it’s a boolean value which specifies that audio will start playing
once it’s ready.
o loop – it’s also a boolean value which specifies looping (means it
automatically start playing after it ends).
o preload – auto, metadata and none are the possible values for this attribute.
o auto means plays as it loaded.
o metadata displays audio file’s associated data
o none means not pre-loaded.

3.How can we embed Video in HTML 5?


Same like audio, HTML 5 defined standard way of embedding video files which was
not supported in previous versions/standards. Supported video formats are as
follows:

o MP4
o WebM
o Ogg

Syntax:

<video width=”450″ height=”340″ controls>


<source src=”testVideo.MP4″ type=”video/mp4″>
Your browser does’nt support video embedding feature.
</video>
Description:

<video> tag has associated optional attributes as controls, autoplay, preload, loop,
poster, width, height and other global attributes etc. Controls, loop, preload and
autoplay are already explained above. Others are explained below:

o poster – it’s basically a URL of the image that needs to display until video get
started.
o width – video player width
o height – video player’s height

4.What are the new media element in HTML 5 other


than audio and video?
HTML 5 has strong support for media. Other than audio and video tags, it comes with
the following tags:

<embed> Tag: <embed> acts as a container for external application or some


interactive content such as a plug-in. Special about <embed> is that it doesn’t have
a closing tag as we can see below:

<embed type=”video/quicktime” src=”Fishing.mov”>

<source> Tag: <source> is helpful for multiple media sources for audio and video.

<video width=”450″ height=”340″ controls>


<source src=”jamshed.mp4″ type=”video/mp4″>
<source src=”jamshed.ogg” type=”video/ogg”>
</video>
<track> Tag: <track> defines text track for media like subtitles as:
<video width=”450″ height=”340″ controls>
<source src=”jamshed.mp4″ type=”video/mp4″>
<source src=”jamshed.ogg” type=”video/ogg”>
<track kind=”subtitles” label=”English” src=”jamshed_en.vtt” srclang=”en”
default></track>
<track kind=”subtitles” label=”Arabic” src=”jamshed_ar.vtt”
srclang=”ar”></track>
</video>

5.What is the usage of canvas Element in HTML 5?


<canvas> is an element in HTML5 which we can use to draw graphics with the help of
scripting (which is most probably JavaScript).
This element behaves like a container for graphics and rest of things will be done by
scripting. We can draw images, graphs and a bit of animations etc using <canvas>
element.

<canvas id=”canvas1″ width=”300″ height=”100″>


</canvas>

6.What are the different types of storage in HTML 5?


HTML 5 has the capability to store data locally. Previously it was done with the help
of cookies.
Exciting thing about this storage is that its fast as well as secure.

There are two different objects which can be used to store data.

o localStorage object stores data for a longer period of time even if the
browser is closed.
o sessionStorage object stores data for a specific session.

SessionStorage LocalStorage

It persist data even if the window or tab is closed


It persists data until we close the window or tab in which it

was stored. (but can be explicitly removed or expires).

Values stored in localStorage are shared for all windows


Values stored in sessionStorage are not shared. These will be

visible only to respective window or tab. and tabs from same origin.
Maximum size for localStorage is more between

Maximum size is 5MB. 10-15MB.

Working with localStorage is quite simple and having following methods:

1. localStorage.getItem(key) -> fetch an item from storage against provided key.


2. localStorage.setItem(key, value) -> add an item to storage.
3. localStorage.removeItem(key) -> removes an item from storage against
provided key.
4. localStorage.clear() -> clearing the storage removing all items from it.

7.What are the new Form Elements introduced in HTML


5?
There are a number of new form elements has been introduced in HTML 5 as follows:

o datalist provides functionality for auto-complete feature.


o datetime facilitate selecting a datetime along with Time Zone.
o output represents the result of a calculation.
o keygen generates a key-pair field in a form to implement secure
authentication.
o date is an input field for date and applies validation accordingly.
o month for selecting a month and year in a form input field.
o week for selecting a week and year in an input field.
o time is an input field for selecting time i.e. Hours:Minutes: AM/PM. For
example, 10:30 AM.
o color is an input field for color.
o number that only allows numeric values.
o range is an input field for selecting value within a specified range.
o email is input field for email with standard email validations.
o url is for an URL(Uniform Resource Locator) and validated accordingly.

8.What are the deprecated Elements in HTML5 from


HTML4?
Elements that are deprecated from HTML 4 to HTML 5 are:

o frame
o frameset
o noframe
o applet
o big
o center
o basefront

9.What are the new APIs provided by HTML 5 standard?


HTML 5 standard comes with a number of new APIs. Few of it are as follows:

o Media API
o Text Track API
o Application Cache API
o User Interaction
o Data Transfer API
o Command API
o Constraint Validation API
o History API

10. What is the difference between HTML 5 Application


Cache and regular HTML Browser Cache?
One of the key feature of HTML 5 is “Application Cache” that enables us to make an
offline version of a web application. It allows to fetch few or all of website contents
such as HTML files, CSS, images, javascript etc locally. This feature speeds up the
site performance. This is achieved with the help of a manifest file defined as
follows:

<!doctype html>
<html manifest=”example.appcache”>
…..
</html>

11.Is it possible to get the geographical location of a


user using HTML5?
Yes. It’s quiet possible to get the geographical location of a user using HTML5. As it
has user’s privacy concerns so user’s approval needed. As we discussed above about
new HTML5 API including Media API, Text Track API, Application Cache, User
Interaction, Data Transfer API, Command API etc: HTML5 introduced new
Geolocation API for locating a user’s position.

In order to get user position, getCurrentPosition() method is used as:

navigator.geolocation.getCurrentPosition(show_map);
12.What are HTML5 Semantic Elements? Explain with
Example.
Semantic elements are those elements that clearly explains the purpose or meaning
of the element to user
(developer). For example, <div> and <span> elements in HTML doesn’t explain what
they will contain as contents. On the other hand, <img> and <form> elements clearly
explains the contents it can contain.

HTML5 introduces many new semantic elements:

o <header>
o <nav>
o <aside>
o <section>
o <article>
o <footer>
o <details>
o <figure>
o <figcaption>
o <main>
o <mark>
o <nav>
o <summary>
o <time>

13.Article Vs Section tags in HTML5?


An <article> tag is a complete and independent piece of content of a document or
page. For Example, this article about HTML5 interview Question is a complete and
independent piece of content on this page that covers a specific topic.

On the other hand, <section> tag refers to specific section of a document or page for
grouping purpose. For Example, at the end of this page, we have a specific section
for related list of “Top Interview Questions And Answers Series”. Or in right nav, we
have a section for “Top Posts and Pages” of this website.

An <article> can wrap a <section> to represents a sub-topic as follows:

<article>
<h1>Interview Questions Series</h1>
<p>List of Interview Questions on Java>
<section>
<h1>HTML5 Interview Questions</h1>
<p>List of Interview Questions on HTML5</p>
</section>
<section>
<h1>JavaScript Interview Questions</p>
<p>List of Interview Questions on JavaScript</p>
</section>
<section>
<h1>ASP.NET MVC Interview Questions</p>
<p>List of Interview Questions on ASP.NET MVC</p>
</section>
</article>

14.What is an HTML5 Web Worker and what all are the


limitations of HTML5 Web Worker?
Normally if some script is executing in an HTML page, the page remains unresponsive
until the scripts execution stops. But an HTML5 web worker is a script (i.e.
JavaScript) that keeps executing in background. At the same time user can interact
with the page and will not feel any performance degradation.

HTML5 web worker normally exists in external files and used for long-running CPU
intensive tasks but without affecting the User Interface or other scripts.

Limitations:

Few JavaScript objects are not accessible to HTML5 web worker as:

o parent object
o window object
o document object

15.Canvas Vs SVG?

Canvas SVG

Multiple Graphics Elements including


Only ONE HTML Element for rendering graphics i.e.

canvas element (Circle, Rect, Boxes, Path, Line, Polygon etc.)

Draws Graphics on the fly using only Script i.e.

JavaScript. Support Script as well as CSS.


Primarily based on Pixels. Based on Graphics elements as discussed above.

Can manipulate by attaching event handlers


No manipulation using Event Handling due to pixel

based interaction. to SVG elements.

Better in Performance. Slow in rendering when manipulating complex scenarios

16. How HTML5 is different from HTML?


HTML5 renders rich web contents without using any additional plugins as compared
to previous HTML versions/standards.

HTML5 comes with a lot new things as follows:

o New multimedia elements that supports for embedding audio, video and
much more.
o Support for interactive graphics.
o New Form elements introduced in HTML5 including datalist, datetime,
output, keygen, date, month, week, time, number, range, email, url etc.
o Elements deprecated in HTML5 are frame, frameset, noframe, applet, big,
center etc.
o New APIs (Media API, Text Track API, Application Cache, User Interaction,
Data Transfer API, Command API etc.) provided.
o HTML5 supports on different plateform like PC, TV , Mobile devices etc.
o Supporting web applications for offline data storage.

17. What are the Data attributes in HTML5?


Data- attributes in HTML5 facilitates us to embed custom data to an element.
Consider a scenario where we have some sensitive or private data related to a
particular page or application without relevant attributes or elements, data-
attributes can be used to serve the purpose.

There are few constraints in using data- attribute

o starts with “data-“


o at least one character after “data-“
o no upper case character in attribute name
o attribute value must be a string
18. What is SVG?
SVG – Scalable Vector Graphics is a vector image format based on W3C SVG
specification. It’s used to draw two-dimensional graphics that are:

o more lightweight as compared to other image formats like jpeg and gif etc.
o XML-based
o support for animation
o maintain better quality even if re-sized
o faster rendering

19.What all are the browser support for local storage in


HTML5?
Browser support for localStorage in HTML5 is as follows:

o Chrome 4
o IE 8+
o firefox 3.5+
o Safari 4
o Opera 10.5

20. What is Local storage in HTML5?


In order to store data locally, HTML5 supports for localStorage object. It stores data
for a longer time in a client browser but it doesn’t lost data even if browser is
closed. This purpose was achieved previously with the help of Cookies.

localStorage has following advantages as compared to using Cookies:

o localStorage has better performance even for larger amount of data.


o localStorage can store data for longer period.
o localStorage is more secure as compared to cookies.

You might also like