Q) Generic syntax
Q) Features of C#
Q) validation controls in ASP.Net
Q) How to apply remoting?
DotNet remoting provides an abstract approach to
interprocess communication that separates the remotable object from a specific
client or server application domain and from a specific mechanism of
communication. There are two ways:
1)
Either
add serializable attribute to the class OR
2)
Inherit
the class from MarshalByRefObject
Q) Cookies
Cookie is a solution in situations where we want to
remember some data for a particular page and for a specific user so that same
data can be used in other pages requested by the same user.
1)
One
of the important State management technique which is a Name-Value
pair which on behalf of server saved in client machine (either in memory or
file).
2)
Once
saved, browser automatically includes this name value pair along with every
request it submits to that server.
3)
Cookies
are used for sharing data across web forms requested by same user/client.
4)
Common
Examples of Cookies
a)
Authenticated
user information
b)
User
specific settings on the site
c)
Shopping
cart
We want to use some information again and again such as
selection of items by a user in shopping cart site, we can use cookies.
5)
Cookies
generated on server (added to the response) are added to the browser through a HTTP Response Header called “Set-Cookie”.
Set-Cookie:name=VALUE;expires:DATE;path:PATH;domain:DOMAIN_NAME;secure=IsHTTPS. These attributes are used by browser for deciding
whether to include the cookie in the request or not (based on the URL of the
request).
6)
With
every request the browser automatically includes all the cookies appropriate to
that request. The Cookie Name- value pairs are submitted in the form of HTTP Request Header called “Cookie” and they are
saved on the server in the form of CGI environmental variable(Server Variable)
called as HTTP_COOKIE.
Cookie:
N1=v1, N2=v2, N3=v3.
Note: Domain, path, expires, and secure attributes are not
included with a cookie in the request. but these values are compared while
sending response. For example if the Url is like www.microsoft.com
Types of Cookies:
1)
Persistent
cookies: A cookie which is permanently saved in a file. For example, these type
of cookies can be shared among all the instances of IE but not to firefox. 2) Non-persistent cookie: These cookies are
temporarily saved in the browser’s temporary memory not in file. These are not
shared across browser instance and are also called as Session Cookie. For
example every instance of IE will have different set of Non-Persistent Cookies.
Programming Cookies:
1)
Request.Cookies is
a collection of HttpCookie objects constructed for every cookie included in the
request.
2)
Response.Cookies is
a collection of HttpCookie objects created for every cookie to be included in
the response so that these cookies can be appended to the existing list of
cookies on the client machine.
Default values for the properties of
Cookie
1)
value=””
2)
path=”/”
3)
Expires=(if
not set then it’s a non-persistent cookie)
4)
Domain=”Current
domain of the website”
5)
Secure=false
Limitations of Cookies:
1)
300
total cookies
2)
4
kilobytes per cookie (max size of cookie)
3)
20
cookies per server or domain
Q) What are Extension Methods?
Extension methods are static methods
which allow you to easily extend a type, such as an integer or string, without
re-compiling or modifying the type.
Extension methods are available from 3.5 version of .Net framework.
One downside: An extension method is only called when there is no
native method found. For example, assume that you created a method by
name “GetFirstThreeCharacters(this String str)” on type String, but this method
already exists in System.String then native method will be preferred over the
extension.
How To Create and Extension Method?
1)
Create
a public static class (module in VB)
2)
Define
functions that you wish to perform and Make the functions as static.
3)
Add
“this” keyword to the first parameter of the extension method (in C#).
Note: The first parameter specifies which type the method
operates on. “this” keyword basically tells the CLR that when this extension
method is called, to use "this" parameter as the source.
public static class MyExtensions
{
public
static int GetNumberOfCharacters(this String str)
{
return
str.Length();
}
}
How to use in other projects?
Copy the namespace alongwith you project and use “Using <namespace>” in your project and start
using the extension methods.
Q) What is COM?
Microsoft COM (Component Object Model) technology in the
Microsoft Windows-family of Operating Systems enables software components to
communicate. COM is used by developers to create reusable software components,
link components together to build applications, and take advantage of Windows
services. COM objects can be created with a variety of programming languages.
Object-oriented languages, such as C++, provide programming mechanisms that
simplify the implementation of COM objects. The family of COM technologies
includes COM+, Distributed COM (DCOM) and ActiveX® Controls.
Q) Difference between & and
&& and also difference between | and ||?
& and &&, both are ‘AND’ operator but basic
difference between is in the way they are executed. For both, syntax is same:
bool_exp1 && bool_exp2
bool_exp1 & bool_exp2
&&: In the first statement, first bool_exp1 will be executed
and then the result of this expression decides the execution of the other
statement. If it is false then the AND will be false so it makes no sense to execute
the other statement. The bool_exp2 statement is executed if and only if
bool_exp1 returns true on execution.
&: Now in the case of & things are different. The
compiler will execute both statements and then the result will be ANDed. It’s
an inefficient way of doing things because it makes no sense to execute the
other statement if one is false because the result of AND is effective only for
ANDing results evaluated to “true” and it’s possible when both statements are
true.
||: It’s the same as above, in the case of “||” only one
statement is executed and if it returns “true” then the other statement will
not be executed. But if the first is false then the other will be checked for
the value “true”. The reason for this is the way the “or” operator works. The
“Or” operator depends on only one true, in other words if any of the
expressions are true then the result will be true.
|: That’s OK but the way “|” behaves is the same as that of
“&”, in other words both statements are executed regardless of the result
of one statement. Check the following example and it will be clear.
CONCLUSION: Use && and || instead of & and |.
Q) How to get system(local i.e
windows) user id and password?
system.environment.getenvironmentvariable( username )
Q) Difference between Finalise() and Dispose() methods?
Finalise
|
Dispose
|
Used to free unmanaged resources like
files, database connections, COM etc. held by an object before that object is
destroyed.
|
It is used to free unmanaged resources
like files, database connections, COM etc. at any time.
|
Internally, it is called by Garbage
Collector and cannot be called by user code.
|
Explicitly, it is called by user code
and the class implementing dispose method must implement IDisposable
interface.
|
It belongs to Object class.
|
It belongs to IDisposable Interface.
|
Implement it when you have unmanaged
resources in your code, and want to make sure that these resources are freed
when the Garbage collection happens.
|
Implement this when you are writing a
custom class that will be used by other users.
|
There is performance costs associated
with Finalize method.
|
There is no performance costs
associated with Dispose method.
|
For Example,
// Implementing Finalize method
public class MyClass
{
//At runtime C# destructor is
automatically Converted to Finalize method.
~MyClass ()
{
//TO DO: clean up unmanaged objects
}
}
|
For Example,
// Implementing Dispose method
public class MyClass : IDisposable
{
private bool disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool
disposing)
{
if (!disposed)
{
if (disposing)
{
//TO DO: clean up managed objects
}
//TO DO: clean up unmanaged objects
disposed = true;
}
}
}
|
Q) What is Collections?
For many applications, you want to create and manage
groups of related objects.
There are two ways to group objects:
(1)
by
creating arrays of objects, and
(2)
by
creating collections of objects.
Arrays are most useful for creating and
working with a fixed number of strongly-typed objects.
Collections provide a more flexible way
to work with groups of objects. Unlike arrays, the group of objects you work
with can grow and shrink dynamically as the needs of the application change. For some collections, you can assign a key to any object
that you put into the collection so that you can quickly retrieve the object by
using the key.
A collection is a class, so you must
declare a new collection before you can add elements to that collection.
A generic collection enforces type safety
so that no other data type can be added to it. When you retrieve an element from a generic collection,
you do not have to determine its data type or convert it.
There are many types of collections:
1)
System.Collections.Generic
Classes
2)
System.Collections.Concurrent
Classes
3)
System.Collections
Classes
4)
Visual
Basic Collection Classes
System.Collections will contain the
following:
(1)
ArrayList:
Represents an array of objects whose size is dynamically increased as required.
Implements the IList interface using an array whose size is dynamically
increased as required.
Syntax:
ArrayList arrLst = new Arraylist();
arrLst.Add();
arrLst.Add();
arrLst.Add();
ArrayList dynamically resizes.
(2)
HashTable:
Represents a collection of key/value pairs that are organized based on the hash
code of the key.
Hashtable ht = new Hashtable();
ht["Name"] =
"Shubham";
ht["Address"] =
"Bangalore";
(3)
Stack:
Represents a first in, first out (FIFO) collection of objects.
(4)
Queue:
Represents a last in, first out (LIFO) collection of objects.
System.Collections.Generic will contain
the following:
(1)
Dictionary<TKey,
TValue>: Represents a collection of key/value pairs that are organized based
on the key. E.g:
Dictionary<string,
int>() dict = new Dictionary<string, int>(){{“One”,1},{“Two”,2}};
Dictionary
is faster than Hashtable.
(2)
List<T>:
Represents a list of objects that can be accessed by index. Provides methods to
search, sort, and modify lists.
(3)
Queue<T>:
Represents a first in, first out (FIFO) collection of objects.
(4)
SortedList<TKey,
TValue>: Represents a collection of key/value pairs that are sorted by key
based on the associated IComparer<T> implementation.
(5)
Stack<T>:
Represents a last in, first out (LIFO) collection of objects.
Q) Difference between Hashtable
and Dictionary.
1)
Dictionary
is generic type and hashtable is not a generic type.
2)
Dictionary
is faster than hashtable because there is no boxing/unboxing in Dictionary but
hashtable involves boxing/unboxing.
i.
When
we retrieve the items from Dictionary we will get the records in the same order
we have inserted them. Whereas we add same records in Ha shTable the order is not maintained.
Q) Suppose exception occurs,
which page will be redirected?
try
{
}
catch
{
Response.Redirect(Login.aspx);
}
finally
{
Response.Redirect(Home.aspx);
}
Whatever happens, ‘finally’ will be executed and Home.aspx
will be redirected.
Q) Can we inherit base class
constructor?
No
Q) What is shadowing?
Shadowing (method hiding):
A method or function of the base class is available to the
child (derived) class without the use of the "overriding" keyword.
The compiler hides the function or method of the base class. This concept is
known as shadowing or method hiding. In the shadowing or method hiding, the
child (derived) class has its own version of the function, the same function is
also available in the base class.
Example
Public class BaseClass
{
public
string GetMethodOwnerName()
{
return "Base Class";
}
}
public class ChildClass : BaseClass
{
public
new string GetMethodOwnerName()
{
return "ChildClass";
}
}
Q) How to get data from from
specific row and column in gridview?
Use OnSelectedIndexChanged event and add following sample
code to this event.
aspx code:
<asp:Gridview Id="GrvSample">
<Columns>
<asp:BoundField DataField="AuthName"
HeaderText="AuthName" SortExpression="AuthName" />
<asp:BoundField
DataField="Title" HeaderText="Title"
SortExpression="Title" />
<asp:BoundField
DataField="Price" HeaderText="Price"
SortExpression="Price" />
<asp:ButtonField Text="Select"
CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:gridView>
<asp:Label ID="lblValues"
runat="server" Text=""></asp:Label>
c# code:
protected void GrvSample_OnSelectedIndexChanged(object
sender, EventArgs e)
{
string authName
= GrvSample.SelectedRow.Cells[0].Text; //1st column
string title =
GrvSample.SelectedRow.Cells[1].Text; //2nd column
string price =
GrvSample.SelectedRow.Cells[2].Text; //3rd column..so on
LblAuthName.Text
= "Selected Author's name is: " + authName + ", book name is:
"+ title + "and price is: " + price;
}
Q) Does event has a return type?
No
Q) Does the following case is
method overloading?
Class C
{
public
string somemethod(int a){}
public
int somemethod(string b){}
}
No, The above will give compilation error as the return types are different for the same method.
For method overloading arguments should be different but not the return type.
Q) How to set paging in gridview?
Use PageIndexChanging
event and write the following sample code:
//Implement page indexing
protected
void GrvSample_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GrvSample.PageIndex = e.NewPageIndex;
//GetBooks method will bring the list of books from the
database.
GrvSample.DataSource
=GetBooks();
GrvSample.DataBind();
}
Q) What is multilevel
inheritance? Do you have used in your project.
Class A
{
public
void MthdA()
{
Console.WriteLine("Member of A");
}
}
Class B:A
{
}
Class C:B
{
}
Class Program
{
static
void Main(string[] args)
{
C objC =
new C();
//Here you can observe that
MthA belongs to Class A and it can also be called from C.
//This is multilevel
inheritance.
objC.MthdA();
Console.ReadKey();
}
}
C will have all the features of A, B and
C. This is multilevel inheritance.
Q) What is the flow for a control
present inside user control (web user control)?
Example:
In ascx page:
<asp:TextBox ID=”TxtSample”
runat=”server”></asp:TextBox>
<asp:Button ID=”BtnSample” runat=”server” />
In aspx Page:
When you click the button which is present inside the user
control, the flow will happen like this:
1)
Events
till Page load event of the aspx page will be called first.
2)
If
master page is present then the same will happen for page load.
3)
Then
it will come to page load event of the ascx page.
4)
After
then control event (e.g BtnSample_Click) will be called.
5)
Then
page_prerender event of aspx page will be called.
6)
Then
page_prerender event of the ascx page will be called.
Q) Design Patterns
Gang of Four deals about 23 design patterns. These all
come under creational, structural and behavioural patterns.
Creational patterns: These patterns deal with the process of objects creation
in such a way that they can be decoupled from their implementing system.
1)Abstract Factory pattern:Create instances of several
classes belonging to different families
2)Factory pattern: Create instances of derived classes
3)Singleton: Ensures that a class can has only one
instance
Structural patterns: These patterns deal with the composition of objects
structures. The concept of inheritance is used to compose interfaces and define
various ways to compose objects for obtaining new functionalities.
Behavioral patterns: These patterns deal with the process of communication,
managing relationships, and responsibilities between objects.
1) Chain of Responsibility: Passes a request among a list
or chain of objects.
2) Command: Wraps a request under an object as a command
and passed to invoker object.
3) Interpreter
Q) What is the difference between
object, var and dynamic?
Q) What are
optional and named parameters in c#?
We can specify optional parameters as
follows:
public int SomeFunction(string
optParam=””, int value=1){}
This function can be called in the
following ways:
1) classic way: SomeFunction(“shubh”,2)
2) named way: SomeFunction(value: 2,
optParam: “shubh”)
Q) How many modes
are available for session state?
There are three modes available for
session state.
1) Off
2) Inproc: Session state is stored locally in memory of ASP.NET
worker process.
3) State server: The session state is stored outside of
the ASP.NET worker process and is managed by windows service. The location of the this service is specified by stateconnection string
attribute.
4) Sql server: Session state is stored outside of the
ASP.NET worker process in SQL server database. The location of the database is
specified using the sqlconnectionstring attribute.
Q) Server controls?
There are three types of server controls.
(1) Html server controls (2) Web server
controls (3) Validation controls
Q) runat=’server’
attribute?
This attribute indicates that the element
should be treated as a server control. Server controls are tags that are
understood by the server.
Q) What is state
management technique?
A new instance of the web page is created
each time the web page is posted back to the server and this happens because HTTP is stateless protocol. To preserve the values of the controls
present on the page or to overcome the “stateless” limitation, ASP.NET provides
us a feature to preserve data on both per-page basis and application-wide
basis. These features include
1) Viewstate 2) Control state 3) Hidden
fields 4) Cookies 5) Query string 6) Session state 7) Application state 8)
Profile properties. Again these features are divided into two types. Viewstate, Control state, Hidden fields,
Cookies, Query string belong to client-based state management technique.
Session state, Application state and Profile properties are server-based state
management options.
Q)
What is dynamic type?
The dynamic type enables the operations
in which it occurs to bypass compile-time type checking. Instead, these
operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office
Automation APIs, and also to dynamic APIs such as IronPython libraries, and to
the HTML Document Object Model (DOM).
Type dynamic behaves like type object in
most circumstances. However, operations that contain expressions of type dynamic
are not resolved or type checked by the compiler. The compiler packages
together information about the operation, and that information is later used to
evaluate the operation at run time. As part of the process, variables of type
dynamic are compiled into variables of type object. Therefore, type dynamic
exists only at compile time, not at run time.
Q) What is anonymous type?
Anonymous types provide a convenient way
to encapsulate a set of read-only properties into a single object without
having to explicitly define a type first. The type name is generated by the
compiler and is not available at the source code level. The type of each
property is inferred by the compiler.
var is anonymous type.
var v = new {Amount=108,
ItemName=”MicromaxMobile”}
Anonymous types typically are used in the
select clause of a query expression to return a
subset of the properties from each object in the source sequence.
Q) What is var
type?
Beginning in Visual C# 3.0, variables
that are declared at method scope can have an implicit type var. An implicitly
typed local variable is strongly typed just as if you had declared the type
yourself, but the compiler determines the type. The following two declarations
of i are functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
int i = 10; //explicitly typed
The following example shows two query
expressions. In the first expression, the use of var is permitted but is not
required, because the type of the query result can be stated explicitly as an
IEnumerable<string>. However, in the second expression, var must be used
because the result is a collection of anonymous types, and the name of that
type is not accessible except to the compiler itself.
// Example #1: var is optional because
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
where word[0] == 'g'
select word;
// Because each element in the sequence is a string,
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
Console.WriteLine(s);
}
// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
where cust.City == "Phoenix"
select new { cust.Name, cust.Phone };
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
where word[0] == 'g'
select word;
// Because each element in the sequence is a string,
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
Console.WriteLine(s);
}
// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
where cust.City == "Phoenix"
select new { cust.Name, cust.Phone };
Q) What is difference between var
and dynamic?
var
|
dynamic
|
Introduced in C# 3.0
|
Introduced in C# 4.0
|
Statically typed – This means the type
of variable declared is decided by the compiler at compile time.
|
Dynamically typed - This means the type
of variable declared is decided by the compiler at runtime time.
|
Need to initialize at the time of
declaration.
e.g., var str=”I am a string”;
Looking at the value assigned to the
variable str, the compiler will treat the variable str as string.
|
No need to initialize at the time of
declaration.
e.g., dynamic str;
str=”I am a string”; //Works fine and
compiles
str=2; //Works fine and compiles
|
Errors are caught at compile time.
Since the compiler knows about the type
and the methods and properties of the type at the compile time itself
|
Errors are caught at runtime
Since the compiler comes to about the
type and the methods and properties of the type at the run time.
|
Visual Studio shows intellisense since
the type of variable assigned is known to compiler.
|
Intellisense is not available since the
type and its related methods and properties can be known at run time only
|
e.g., var obj1;
will
throw a compile error since the variable is not initialized. The
compiler needs that this variable should be initialized so that it can infer
a type from the value.
|
e.g., dynamic obj1;
will compile;
|
e.g. var obj1=1;
will compile
var obj1=” I am a string”;
will throw error since the compiler has
already decided that the type of obj1 is System.Int32 when the value 1 was
assigned to it. Now assigning a string value to it violates the type safety.
|
e.g. dynamic obj1=1;
will compile and run
dynamic obj1=” I am a string”;
will compile and run since the compiler
creates the type for obj1 as System.Int32 and then recreates the type as
string when the value “I am a string” was assigned to it.
This code will work fine.
|
Q) What is connection pool?
In practice, most
applications use only one or a few different configurations for connections.
This means that during application execution, many identical connections will
be repeatedly opened and closed. To minimize the
cost of opening connections, ADO.NET uses an optimization technique called
connection pooling.
Connection
pooling reduces the number of times that new connections must be opened. The
pooler maintains ownership of the physical connection. It
manages connections by keeping alive a set of active connections for each given
connection configuration. Whenever a user calls Open on a connection,
the pooler looks for an available connection in the pool. If a pooled
connection is available, it returns it to the caller instead of opening a new
connection. When the application calls Close on the connection, the pooler
returns it to the pooled set of active connections instead of closing it. Once
the connection is returned to the pool, it is ready to be reused on the next
Open call.
Only
connections with the same configuration can be pooled. By default, connection
pooling is enabled in ADO.NET.
Q) What is an application pool?
The
<applicationPools> element contains configuration settings for all
application pools running on your Internet Information Services (IIS) 7 or
later server. An application pool defines a group of one or more worker
processes, configured with common settings that serve requests to one or more
applications that are assigned to that application pool. Because application
pools allow a set of Web applications to share one or more similarly configured
worker processes, they provide a convenient way to isolate a set of Web
applications from other Web applications on the server computer. Process
boundaries separate each worker process; therefore, application problems in one
application pool do not affect Web sites or applications in other application
pools. Application pools significantly increase both the reliability and
manageability of your Web infrastructure.
What is worker process?
An Internet
Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is
responsible for handling requests sent to a Web Server for a specific
application pool.
IIS 7 lists worker processes with associated
application pool names, and provides the following information for each worker
process:
1) Application
Pool Name. The name of the application pool. In the case of Web gardens, the
same application pool may be listed more than once in the grid to account for
different worker processes running in the application pool.
2) Process ID.
The worker process identifier (ID) associated with the application pool.
3) State. The
state of the process, such as starting, running, or stopping.
4) CPU %. The
percentage of time that the worker process has used the CPU since last update.
This corresponds to CPU Usage in Task Manager.
5) Private Bytes
(KB). The current size of memory committed to a worker process, which cannot be
shared with other processes. This corresponds to Virtual Memory Size in Windows
Task Manager.
6) Virtual Bytes
(KB). The current size of the virtual address space for a worker process. This
does not correspond to anything in Windows Task Manager.
Q) What are the 4 pillars of any object oriented programming language?
1. Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism
Q) Abstraction.
It is
"To represent the essential feature without representing the background
details." Abstraction lets you focus on what the object
does instead of how it does. Abstraction provides you a generalized view of
your classes or object by providing relevant information. Abstraction is the
process of hiding the working style of an object, and showing the information
of an object in understandable manner.
Real
world Example of Abstraction-1:
Suppose you have
an object Mobile Phone. Suppose you have 3 mobile phones as following:-
Nokia 1400
(Features: Calling, SMS)
Nokia 2700
(Features: - Calling, SMS, FM Radio)
Blackberry
(Features: - Calling, SMS, FM Radio, MP3)
Abstract
information (Necessary and Common Information) for the object "Mobile
Phone" is make a call to any number and can send SMS." so that, for
mobile phone object you will have abstract class like following:-
abstract class
MobilePhone
{
public
void Calling () {}
public void SMS
() {}
}
public class
Nokia1400 : MobilePhone
{
}
public class
Nokia1600 : MobilePhone
{
public
void FMRadio() {}
}
public class
BlackBerry : MobilePhone
{
public sub FMRadio() {}
public sub MP4() {}
}
Abstraction
means putting all the variables and methods in a class which are necessary. For example: -
Abstract class and abstract method. Abstraction is the common thing.
Real
world Example of Abstraction-1:
If somebody in
your college tell you to fill application form, you will fill your details like
name, address, date of birth, which semester, percentage you have got etc. If
some doctor gives you an application to fill the details, you will fill the
details like name, address, date of birth, blood group, height and weight.
See in the above
example what is the common thing? Age, name, address. So you can create the
class which consists of common thing that is called abstract class. That class
is not complete and it can be inherited by other class.
Q) Inheritance.
Inheritance
enables you to create new classes that reuse, extend, and modify the behavior
that is defined in other classes. The class whose members are inherited is
called the base class, and the class that inherits those members is called the
derived class. A derived class can have only one direct base class (no multiple inheritance). However, inheritance is transitive. If ClassC is derived
from ClassB, and ClassB is derived from ClassA, ClassC inherits the members
declared in ClassB and ClassA.
Q) Polymorphism.
Polymorphism is
often referred to as the third pillar of object-oriented programming, after
encapsulation and inheritance. Polymorphism is a Greek word that means
"many-shaped" and it has two distinct aspects:
1) At run time,
objects of a derived class may be treated as objects of a base class in places
such as method parameters and collections or arrays. When this occurs, the
object's declared type is no longer identical to its run-time type.
2) Base classes
may define and implement virtual methods, and derived classes can override
them, which means they provide their own definition and implementation. At
run-time, when client code calls the method, the CLR looks up the run-time type
of the object, and invokes that override of the virtual method. Thus in your
source code you can call a method on a base class, and cause a derived class's
version of the method to be executed.
Polymorphism
provides following features:
1) It allows you
to invoke methods of derived class through base class reference during runtime.
2) It has the
ability for classes to provide different implementations of methods that are
called through the same name.
Polymorphism
is of two types:
1) Compile time
polymorphism/Overloading
2) Runtime polymorphism/Overriding
Compile
Time Polymorphism: Compile time polymorphism is method and
operators overloading. It is also called early binding. In method overloading
method performs the different task at the different input parameters.
Runtime
Polymorphism: Runtime polymorphism is done using inheritance
and virtual functions. Method overriding is called runtime polymorphism. It is
also called late binding.
Note: While overriding
a method, you can change the behavior of the method for the derived class. Overloading
a method simply involves having another method with the same prototype.
Q) Encapsulation.
Wrapping
up data member and method together into a single unit (i.e. Class) is called
encapsulation. Encapsulation is like enclosing in a capsule.
That is enclosing the related operations and data related to an object into
that object. Encapsulation is like your bag in which you can keep your pen,
book etc. It means this is the property of encapsulating members and functions.
class Bag
{
book;
pen;
ReadBook();
}
Encapsulation
means hiding the internal details of an object, i.e. how an object does
something. Encapsulation prevents clients from seeing it’s
inside view, where the behaviour of the abstraction is implemented. Encapsulation
is a technique used to protect the information in an object from the other
object.
Hide
the data for security such as making the variables as private, and expose the
property to access the private data which would be public. So, when you
access the property you can validate the data and set it.
Example:
class Demo
{
private int _mark;
public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value;
else _mark = 0; }
}
}
Real
world Example of Encapsulation-1:
Let's take
example of Mobile Phone and Mobile Phone Manufacturer. Suppose you are a Mobile
Phone Manufacturer and you designed and developed a Mobile Phone design(class),
now by using machinery you are manufacturing a Mobile Phone(object) for
selling, when you sell your Mobile Phone the user only learn how to use the
Mobile Phone but not that how this Mobile Phone works.This means that you are
creating the class with function and by making object (capsule) of it you are
making availability of the functionality of your class by that object and
without the interference in the original class.
Real
world Example of Encapsulation-2:
TV operation: It
is encapsulated with cover and we can operate with remote and no need to open
TV and change the channel. Here everything is in private except remote so that
anyone can access not to operate and change the things in TV.
Q) Difference between Abstraction and Encapsulation.
Abstraction
|
Encapsulation
|
1. Abstraction solves the problem in the design level.
|
1. Encapsulation solves the problem in the implementation level.
|
2. Abstraction is used for hiding the unwanted data and
giving relevant data.
|
2. Encapsulation means hiding the code and data into a
single unit to protect the data from outside world.
|
3. Abstraction lets you focus on what the object does
instead of how it does.
|
3. Encapsulation means hiding the internal details or
mechanics of how an object does something.
|
4. Abstraction- Outer layout, used in terms of design.
For Example:-
Outer Look of a
Mobile Phone, like it has a display screen and keypad buttons to dial a
number.
|
4. Encapsulation- Inner layout, used in terms of
implementation.
For Example:- Inner Implementation detail of a Mobile
Phone, how keypad button and Display Screen are connect with each other using
circuits.
|
Q) What is .Net Framework?
.Net framework is
a technology on which .Net applications are built and deployed. The framework
consists of three main components:
(1) Common Language Runtime.
(2) Framework Base classes (Base Class Library) like
System.IO, System.Threading and many more.
(3) User and Program Interface - Like User
Interface(ASP.NET, WPF, etc) and Program Interface (C#, J#, VB.NET, F#, etc).
It is used to
build and run windows and web applications.
Q) Common Language Runtime
Common
Language Runtime (CLR) is a managed execution environment that is part of
Microsoft’s .NET framework. CLR manages the execution of programs
written in different supported languages.
How
it works? The .NET compiler converts the code written in a
supported .NET language, such as C# or VB.Net to CIL (Common Intermediate
Language) code. During runtime, the CLR converts the CIL code into native code
that can be understood by the operating system. It provides services such as memory management, thread management, security
management, code verification, compilation and other system services.
Q) Managed code and unmanaged code?
Managed Code:
The code which is written in (vb.net, c#, j#) .net framework language is called
as managed code which is under the
control of CLR. Garbage collector run automatically in managed code. In
other words, code that we develop with a language compiler that targets the
runtime is called managed code. It benefits
from features such as cross-language integration,
cross-language exception handling, enhanced security, versioning and deployment
support, a simplified model for component interaction, debugging and profiling
services.
UnManaged Code: The code which is produced by third party language is
called as unmanaged code, which does not run under the control of CLR.
Garbage collector will not run in case of unmanaged code.
Q) What is an assembly?
1) An assembly is a fundamental building block of any .NET
Framework application. For example, when you build a simple C#
application, Visual Studio creates an assembly in the form of a single portable
executable (PE) file, specifically an EXE or DLL.
2) An assembly is
the smallest unit of reuse, versioning and security.
3) Assemblies
contain metadata that describe their own internal version number and details of
all the data and object types they contain.
4) Assemblies can be an efficient way to manage resources in
larger projects because they are only loaded as they are required. If they are
not used, they are not loaded.
Q) What is a metadata?
Metadata includes description of an assembly. Description includes type definitions, version
information, external assembly references,
security permissions and other standard information. During compile
time, metadata is created with MSIL (Microsoft Intermediate Language) and
stored in a file called ‘Manifest’. An
assembly manifest contains all the metadata needed to specify the assembly's
version requirements and security identity, and all metadata needed to define
the scope of the assembly and resolve references to resources and classes. The
assembly manifest can be stored in either a PE file (an .exe or .dll) with
Microsoft intermediate language (MSIL) code or in a standalone PE file that
contains only assembly manifest information.
Benefits of
Metadata: Metadata provides great benefits such as self-describing files, language interoperability, type
safety and is extensible through attributes.
Q12) Connectionstring description?
1) Data Source - It identifies the server, can be a
local machine, machine domain name or IP Address.
2) Initial Catalog - name of the database.
3) Persist Security Info - specifies whether the data source can persist
sensitive authentication information such as a password. It can be set as true or false.
4) User ID - name of the user configured in SQL
server.
5) Password - password set in SQL server for this
User ID.
Q13) What is the difference between string and stringbuilder?
String
object is immutable and StringBuilder is mutable. By immutable
means that string object cannot be changed. So, if you were to do some string
operation involving an append or trim or some other method call to modify your
string object, you would really be creating those
many new objects of class String. Performance will degrade and hence we
will use StringBuilder. If you will store string in StringBuilder and will do some operation,
then it will do the operation on this same object and it will not create other
object.
Note:
Creating more number of objects is expensive because it consumes memory.
Q14) What is struct?
A struct is a
value type that contains constructors, constants, fields, methods, properties,
events, indexers, operators and nested types.
Syntax:
[attributes] [modifiers] struct identifier : <interfaceNames> {
}. This is explained below:
(1) attributes (Optional):
Additional declarative information.
(3) identifier:
The struct name.
(4)
interfacenames (Optional): A list that contains the interfaces implemented by
the struct, all separated by commas.
(5) {}: The
struct body that contains member declarations.
Example:
public struct
Point
{
public int x, y;
public int point(int p1, int p2)
{
x = p1;
y = p2;
}
}
Some
points about structs:
1) Struct is a
value type while class is a reference type.
(2) In some
scenarios, struct is less expensive than class.
(3) There is no
inheritance for structs. But structs can implement interface.
(4) Variables
directly contain the data of the struct a while variable of a class type
contains a reference to the data. This means that with structs you avoid the
overhead of objects in the C# language. You can combine multiple fields. This
reduces memory pressure. And it improves performance if the stack is not
overwhelmed.
Do structs support inheritance?
No, structs do
not support inheritance, but they can implement interfaces.
Q15) What is the main advantage of using inheritance?
Code reuse
Q16) Can we open Web.Config file through URL?
We can’t because
it is not served by IIS for security reasons. It contains “database connection
string”.
Q17) Can we host Web Service outside of IIS?
We can host web
services outside of IIS also. Possibilities are
1) Windows Services
2) Console Applications
3) COM+ components or windows form
applications
Q18) What is viewstate and its advantages and disadvantages?
Viewstate
is a technique used by ASP.Net web pages to keep the state of the page across
post backs. It stores data in a hidden field name _VIEWSTATE inside the page in base 64 encoded format. The viewstate will exist
till the life of that page.
Advantage:
1) It does not require
any server resource. It is stored at client side.
2) Automatically
retains the state of the page.
3) Provides the
flexibility to enable or disable at page or control level.
4) Also provide
control to check and validate whether the view state data is tampered or not by
using EnableViewStateMac.
Disadvantage:
1) Since the view
state data is stored inside the page it increases the network overhead as all
the data travel along with the page.
2) As data is
stored in encoded format, it can be easily decoded. So it is advised not to
store sensitive data in viewstate.
EnableViewState?
Gets or sets a
value indicating whether the page maintains its view state, and the view state
of any server controls it contains, when the current page request ends.The
default is true. Either we can set this property in page directive for the
whole page or we can set it inside individual controls.
What is EnableViewStateMac?
Gets or sets a
value indicating whether ASP.NET should check message authentication codes
(MAC) in the page’s view state when the page is posted back from the client.
The main purpose is to check whether the data present on the client is tampered
or not. By default the value is true.
Q) Does C# support multiple inheritance ? If No Why?
No. Because of
‘Diamond’ problem.
Q) What is diamond problem?
Or
Why C# does not support multiple
inheritance?
In
object-oriented programming language with multiple inheritance and knowledge
organization, the diamond problem is an ambiguity that arises when two classes
B and C inherit from A, and class D inherits from both B and C. If a method in
D calls a method defined in A (and does not override the method), and B and C
have overridden that method differently, then from which class does it inherit:
B, or C?
Q) What is interface?
An
interface contains only the signatures of methods, properties, events or
indexers. A class or struct that implements the interface must implement the
members of the interface that are specified in the interface definition. In the following
example, classImplementationClass must implement a method named SampleMethod
that has no parameters and returns void.
interface ISampleInterface
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}
static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
}
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}
static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
}
Q) Why we need interface?
(1) To extend the
functionality of base class.
(2) To take the
advantages of polymorphism by using interfaces.
(3) For naming
convention, say you are working in team and each member has to use one common
method for e.g Draw. So we will define this method in IDraw Interface and every
member can use this method.
(4) To implement
multiple inheritance because multiple inheritance is not allowed in C#.
(5) For removing
dependency (E.g ZEWS solution).
Q) Can we use access specifiers for interface?
No. All methods in an interface are public by
default so we cannot use any access specifiers. If we will use, it will show
error.
Q) Access specifiers for classes?
Classes at the
namespace level can be public or internal only. We can't use private, protected
or protected internal for classes at namespace level. All access specifiers are
applicable for nested classes ie. nested classes can be public, private, protected
or internal or protected internal.We can use any access specifiers for methods
and nested classes.
Q) What is keyword for inherit and implements in c#?
Colon i.e ':' is
used for both. If you are implementing more than one interface for a class then
use comma. When inheritance of a class and implementation of interface has to
be done at same time then priority will be for inheritance of class than
implementation of interface. For example check the example shown below:
Example: For inheriting MainClass and implementing
three interfaces ->
Class Test : MainClass, ITest1,
ITest2, ITest3
{
// Write the code
here
}
Q) Details about interface?
An interface is a
named collection of method definitions and their signatures without
implementation.
(1) Only methods
and signatures(i.e declaration part and not implementation) are required.
(2) Interface
members must be methods, properties, events or type definitions.
(3) All methods
in an interface are public by default so we cannot use any access specifiers
otherwise it will generate error.
(4) A class that
implements the interface agrees to implement all of the methods defined in the
interface.
Q) Difference between abstract class and interface?
(1) An interface
only provides declaration but abstract class can provide complete, default
and/or just the details that have to be overridden.
(2) A class can
implement more than one interface but can inherit only one abstract class.
(3) An interface
cannot have access specifiers but abstract class can contain the access
modifiers for subs, properties and functions.
(4) Requires more
time to find the actual method in the corresponding classes. But abstract
classes are fast.
(5) No fields can
be defined in interfaces. An abstract class can have fields and constraints
defined.
(6) If we add a
new method to an Interface then we have to track down all the implementations
of the interface and define implementation for the new method. If we add a new
method to an abstract class then we have the option of providing default implementation
and therefore all the existing code might work properly.
(7)
If various implementations only share method signatures then it is better to
use Interfaces.If various implementations are of the same kind and use common
behaviour or status then abstract class is better to use.
In conclusion we
can say that interface is an abstract class which provides only declaration and
not any other thing.
Q) In which cases we will not be able to create object of class?
We will not be
able to create an object of a class in the following scenarios:
(1) When you
declare the constructor as private.
(2) When you
declare the class as static.
(3) When you
declare the class as abstract.
(4) When you
declare the class as not class but interface.
Q) Garbage Collection in Short?
The
.Net Framework garbage collector manages the allocation and deallocation of
memory for your application. Each time we create a new object, the
common language runtime allocates a memory for the object from the managed
heap. As long as address space is available in the managed heap, the runtime
continues to allocate space for the new objects. However, the memory is limited. Eventually
the garbage collector must perform a collection in order to free some memory.
The garbage collector’s optimizing engine determines the best time to perform a
collection, based upon the allocations being made. While performing a
collection, it checks for objects in the managed heap that are no longer being
used by the application and performs the necessary operation to reclaim their
memory.
In
short, Garbage collection is
the process of managing the allocation and release of memory which are no
longer in use.
Q) Global Assembly Cache?
Each
computer wherein the common language runtime is installed has a machine-wide
code called the Global Assembly cache. This global assembly cache stores .NET
assembly specifically designated to be shared by several applications on that
computer.
For .NET 4.0, GAC is situated in the following
location:
%windir%\Microsoft.Net\assembly\
For previous
version of .NET Framework, the GAC is
present in the following location:
%windir%\assembly\
Installation of an assembly into GAC:
gacutil –i
<completeAssemblyPath>
Un-installation
of an assembly from GAC:
gacutil –u
<assemblyName>
Link: http://www.codeproject.com/Articles/4352/Demystifying-the-NET-Global-Assembly-Cache
Q) How .Net Framework make transitions between managed and unmanaged
code?
.NET Framework uses DCOM for making transition between
managed and unmanaged code.
Q) What is type safe?
Type safety means that the compiler will
validate types while compiling,
and throw an error if you try to assign the wrong type to a variable.
In computer
science, type safety is the extent to which a programming
language discourages
or prevents type errors. A type error is erroneous or undesirable program
behaviour caused by a discrepancy between differing data types for the program's constants, variables, and methods
(functions),for e.g., treating an integer (int) as a floating-point number
(float).
Q) What is type casting (or
casting)?
Conversion between data types is called as type casting.
In implicit conversion (from smaller to large data types for example, int to
float or from base class to derived class), type casting is not required as it
will not throw error but while explicit conversion casting is required.
Example:
C#:
double x = 1234.7;
int a = (int)x; // cast double to int
int a = (int)x; // cast double to int
VB:
Dim str As
String = "300"
Dim num As Integer =
CInt(str)
C#.Net supports 2 types of typecasting:
1)Implicit type casting.
2)Explicit type casting.
Implicit type casting is under control or CLR. Converting from Lower data types
into Higher data types is called as Implicit type casting.
For Example:
Byte---->Long(Implicit)
Explicit type casting is under control of programmer. Converting from Higher
data types into Lower data types is called as Explicit type casting.
For Example:
long---->int(Explicit)
C#.Net supports 4 types of Explicit Type
Casting:
1)C++ style of TypeCasting. E.g. a = (int)x;
2)Converting. E.g. Convert.ToString, Convert.ToInt32.
3)Parsing. E.g. Int.Parse() in c# and Integer.Parse()
4)Boxing & UnBoxing.
Q) What is Option Explicit?
1) If used, the Option Explicit statement
must appear in a file before any other source code statements.
2) When Option Explicit appears in a
file, you must explicitly declare all variables using the Dim or ReDim statements.
If you attempt to use an undeclared variable name, an error occurs at compile
time.
Q) Why C# is a strongly typed
language?
Before a value can be stored in a variable, the type of
the variable must be declared and also type of value must be matched with the
data type. If datatype is not correct then it will throw compile time error.
Q) Conversions?
1) Implicit conversion:
No special syntax is required because the conversion type is safe and no date
will be lost. Examples include conversions from smaller to larger integral
types, and conversions from derived classes to base classes.
2) Explicit conversion:
Explicit conversion require a cast operator. Casting is required when
information might be lost in the conversion, or when the conversion might not
succeed for other reasons. Typical examples include numeric conversion to a a
type that has less precision or a smaller range, and conversion of a base class
instance to a derived class.Using explicit conversions we are actually letting
the compiler know that we know there is possible information loss but still we
need to make this conversion. So if we need to convert a long type to an
integer type we need to cast it explicitly.
3) User defined conversions:
User defined conversions are performed by special methods that you can define
to enable implicit and explicit conversions between custom types that do-not
have a base class-derived class relationship.
4) Conversion with helper
classes: To convert between non-compatible types, such as integers and
System.Datetime objects, or hexadecimal strings and byte arrays, we can use the
System.BitConverter class, the System.Convert class and the parse methods of
the built-in numeric types, such as Int32.Parse.
Q) Can a class can contain a class?
Yes, nested classes
can exist.
Q) Suppose you have set two master pages for a content pages, in which
event you will set master pages for a content page dynamically?
Page_PreInit
event of the content page.
void
Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/NewMaster.master";
}
{
this.MasterPageFile = "~/NewMaster.master";
}
Q) What is static modifier?
When we use the static keyword before a class name:
1) We specify that the class will only have static member
variables and methods.
2) Such classes cannot be instantiated as they don’t need
to: they cannot have instance variables.
3) Also, an important point to note is that such static
classes are sealed by default, which means they cannot be inherited further.
4) They cannot contain Instance Constructors or simply
constructors as we know that they are associated with objects and operates on
data when an object is created.
When we use the static keyword before a method or variable
name:
1) Static members and variable can reside in non-static
class.
2) An important point to note is that the static methods
inside a class can only use static member variables of that class.
Example:
Suppose you have a private variable in MyClass which is
not static:
class MyClass
{
// non-static instance member variable
private int a;
//static member variable
private static int b;
//static method
public static void DoSomething()
{
//this will result in compilation error as “a” has no memory
a = a + 1;
//this works fine since “b” is static
b = b + 1;
}
}
{
// non-static instance member variable
private int a;
//static member variable
private static int b;
//static method
public static void DoSomething()
{
//this will result in compilation error as “a” has no memory
a = a + 1;
//this works fine since “b” is static
b = b + 1;
}
}
Now, we will call the DoSomething method as: MyClass.DoSomething();
Note that we have not created any
instance of the class, so the private variable "a" has no memory as when we call a
static method for a class, only the static variables are present in the memory
(in the Static part). Instance variables, such as “a” in the above example, will only be
created when we create an instance of the class using the “new” keyword, as:
Imp Information about static modifier:
1) Only one copy of static fields and
events exists.
2) Static members are often used to represent data or
calculations that do not change in response to object state; for instance, a
math library might contain static methods for calculating sine and cosine.
Q) Why we create an object or
objects of a class?
We create different objects to store and manipulate
different data at different times. When we don’t want any change or
manipulation of the data, that is the data will be same for example in case of
cosine, sine etc. then we will create static class.
Q) Where we can use static
classes?
1) We can use static class when all the members and
variables are static.
2) Use a static class as a
unit of organization for methods not associated with particular objects.
Q) Advantages of static class.
Static class makes implementation simple and faster
because there is no need to create object.
Q) What is default constructor?
A constructor which accepts no parameter is called the
default constructor or parameterless constructor.
Q) What are private assemblies
and shared assemblies?
A private assembly is used only by a single application,
and is stored in that application's install directory (or a subdirectory
therein). A shared assembly is one that can be referenced by more than one
application. In order to share an assembly, the assembly must be explicitly
built for this purpose by giving it a cryptographically strong name (referred
to as a strong name). By contrast, a private assembly name need only be unique
within the application that uses it.
Q) What is the Microsoft
Intermediate Language (MSIL)?
MSIL is the CPU-independent instruction set into which
.NET Framework programs are compiled. It contains instructions for loading,
storing, initializing, and calling methods on objects. Combined with metadata
and the common type system, MSIL allows for true cross-language
integration.Prior to execution, MSIL is converted to machine code. It is not
interpreted.
Q) What are private assemblies
and shared assemblies?
A private assembly is used only by a single application,
and is stored in that application's install directory (or a subdirectory
therein). A shared assembly is one that can be referenced by more than one
application. In order to share an assembly, the assembly must be explicitly
built for this purpose by giving it a cryptographically strong name (referred
to as a strong name). By contrast, a private assembly name need only be unique
within the application that uses it.
Q) Difference between
dataadapter, datareader and dataset?
DataReader : This is best used when you just want to fetch data in
readonly mode , populate your business entity and close the reader. This is
really fast. You cannot do update with datareader. It is forward only, read
only and works in connected mode. it keeps single row at a time.
DataAdapter : You can Read/Update the data with dataadapters but it
is less faster when reading the data then Datareader. It can do read/Write in
both sides and works in disconneted mode. It acts as a bridge between dataset
and datasource. Dataset doesnot interact with datasource, dataadapter fills
does this work.
Dataset: DataSet is a disconnected orient architecture that means
there is no need of active connections during work with datasets and it is a
collection of DataTables and relations between tables. It is used to hold
multiple tables with data. You can select data form tables, create views based
on table and ask child rows over relations. Also DataSet provides you with rich
features like saving data as XML and loading XML data.
Q) Which is the base class for
all classes in .Net Framework?
System.object
Q) Difference between stack and
heap.
1) They are both stored in Computer's RAM.
2) Stack is used for static memory allocation while heap
is used for dynamic memory allocation.
3) Memory block in stack will be freed when thread is
terminated while heap is freed after application termination.
4) Memory block in stack will be freed automatically but
heap memory will be freed by garbage collector.
3) The stack is much faster than heap.
6) Memory allocation and deallocation is done using
LIFO(Last In First Out) in stack while heap can be reached at any time.
Q) Reference type and value type?
Value types:
1) Value types can be created at compile time.
2) Stored in stack memory.
3) Garbage collector can't access the stack
4) Value types holds the data directly
5) No default values will be stored in value types
Examples for value types: Predefined data types,
structures, enums, int
Reference types:
1) Reference types can be created at run time.
2) Stored in heap memory
3) Garbage collector can access heap
4) Reference types holds the data indirectly
5) Reference types holds default value
Examples for reference types: Classes, objects, Arrays,
Indexers, Interfaces, String
Q) AutoEventWireup
The ASP.NET page framework also supports an automatic way
to associate page events and methods.The disadvantage of the AutoEventWireup
attribute is that it requires that the page event handlers have specific,
predictable names. This limits your flexibility in how you name your event
handlers. Therefore, in Visual Studio, the AutoEventWireup attribute is set to
false by default and the designer generates explicit code to bind page events
to methods. If you do set AutoEventWireup to true, Visual Studio will generate
code to bind the events and the page framework will automatically call events
based on their names. This can result in the same event code being called twice
when the page runs. As a consequence, you should always leave AutoEventWireup
set to false when working in Visual Studio.
Q) Differences between
ExecuteReader, ExecuteNonQuery AND ExecuteScalar?
ExecuteNonQuery: ExecuteNonQuery method will return number of rows
affected with INSERT, DELETE or UPDATE operations. This ExecuteNonQuery method
will be used only for insert, update and delete, Create, and SET statements.
ExecuteScalar: ExecuteScalar will return single row single column value
i.e. single value, on execution of SQL Query or Stored procedure using command
object. It’s very fast to retrieve single values from database.
ExecuteReader: ExecuteReader will be used to return the set of rows, on
execution of SQL Query or Stored procedure using command object. This one is
forward only retrieval of records and it is used to read the table values from
first to last.
Q) Differences between datagrid,
repeater, gridview and listview?
Controls
|
ListView
|
GridView
|
DataList
|
Repeater
|
Paging
|
Supported
|
Supported
|
Not Supported
|
Not Supported
|
Data Grouping
|
Supported
|
Not Supported
|
Supported
|
Not Supported
|
Provide Flexible Layout
|
Supported
|
Not Supported
|
Supported
|
Supported
|
Update, Delete
|
Supported
|
Supported
|
Not Supported
|
Not Supported
|
Insert
|
Supported
|
Not Supported
|
Not Supported
|
Not Supported
|
Sorting
|
Supported
|
Supported
|
Supported
|
Supported
|
Introduced in ASP.NET version
|
3.5
|
2.0
|
1.1
|
1.1
|
Q) What is the difference between
datatable.Clone() and datatable.copy()?
The main difference between clone and copy is that Clone
will copy the structure of a datatable whereas Copy will copy the complete
structure as well as data.
Q) What is the difference between
const and readonly?
1) Const value must be known at compile time while
readonly value can be assigned at run time.
2) Const must be assigned when declared but readonly can
be assigned either at declaration time or in the constructor.
2) Const can't be modified within a class or out of the
class where as readonly can be modified in same class.
2) We can use read only when some function value needs to
be calculated at run time.
3) For example:
static class NonModifiableDeclarationSet {
internal const int SomeInteger = 5;
internal const int SomeOtherInteger = SomeInteger * 10; //constant expression
// won't compile:
//internal const double SomeFloatingPointValue = System.Math.Acos(-1d);
// will work:
internal static readonly double SomeFloatingPointValue = System.Math.Acos(-1d);
}
internal const int SomeInteger = 5;
internal const int SomeOtherInteger = SomeInteger * 10; //constant expression
// won't compile:
//internal const double SomeFloatingPointValue = System.Math.Acos(-1d);
// will work:
internal static readonly double SomeFloatingPointValue = System.Math.Acos(-1d);
}
Q) What is the difference between
Asp.Net user control (ascx) and Asp.Net web page (aspx)?
1) User control contains an @Control directive while web
page contains an @Page directive.
2) User controls cannot run as standalone files like aspx
pages. They must be embedded inside aspx pages if they are needed.
3) Base class for User Control is
System.Web.UI.UserControl and for Web forms, it is System.Web.UI.Page
4) The user control does not have html, body or form
elements in it.
5) User control extension is ascx and web page or web
forms extension is aspx.
Q) Similarities between User
control and web page?
1) Use of existing web server controls which Asp.Net
offers.
2) The event model that Asp.Net provides.
3) A user control can include codes such as binding from
database etc...
Q) Differences between master
page and user control?
1) Master Pages are used to provide the consistent layout
and common behaviour for multiple pages in your applications. Then you can add
the Contentplaceholder to add child pages custom content. User Controls are
used at times when you need the functionality in your web pages which is not
possible using the built-In web server controls then user can create his own
controls called user controls using asp.net built-in controls. User controls
are those with .aspx extensions and you can share it in the application.
2) A master page is page template whereas user control encapsulates
a piece of functionality.
3) Extension for master page is .master and extension for
user control is .ascx.
4) Master pages can be referenced using Web.Config file
also or dynamically by writing code in PreInit event. User controls can be
attached dynamically using LoadControl method. PreInit event is not mandatory
in their case for dynamic attachment.
5) User control can be used inside master page but master
page cannot be used inside user control.
6) Master page inherits System.Web.UI.MasterPage and this
MasterPage class inherits System.Web.UI.UserControl
Q) what is session state?
Session state is a state management technique which
provides facility to store information in server memory on a per client basis.
Advantages:
1) Easy to implement and can store any kind of object.
2) Session is secure and transparent from the user.
3) Stores client data separately.
Disadvantages:
1) Performance overhead in case of large data/user,
because session data is stored in server memory.
2) Overhead involved in serializing and deserializing
session data, because in the case of StateServer and SqlServer session modes,
we need to serialize the objects
before storing them.
System.Web.SessionState.HttpSessionState class provides
the built-in session object in ASP.NET pages.
Storing a value in session:
Session["UserName"] = TxtUser.text;
Retrieving a value from session:
If (Session["UserName"]) != null)
{
LblUser.Text =
Session["UserName"];
}
else
{
// Do something
}
Storing a dataset:
Session["DataSet"] = objDataSet;
Retrieving a DataSet session:
If (Session["DataSet"]) != null)
{
DataSet myDataSet =
(DataSet)Session["DataSet"];
}
else
{
// Do something
}
When a client communicates with a server, only the session
ID is transmitted between them. When the client requests for data, ASP.NET
looks for the session ID and
retrieves the corresponding data from the state provider.
In the web.config, <SessionState> elements are used
for setting the configuration of the session. Some of them are Mode, Timeout,
StateConnectionString, CustomProvider,
etc.
Session state can only be used when enableSessionState is
set to true, either in a configuration file or in the Page directive. Please
also make sure that
System.Web.SessionStateModule or a custom session state
module is included in the
<configuration>\<system.web>\<httpModules> section in the
application configuration.
Q) Where session value is stored?
ASP.NET saves the value in state provider. For every
session state, there is a state provider. Session State mode - State provider
1) InProc - In-memory object
2) StateServer - Aspnet_state.exe
3) SQLserver - Database
4) Custom - Custom Provider
There is also one mode "Off". If we select this
option the session will be disabled for the application.
Q What is global.asax file?
1) The Global.asax, also known as the ASP.NET application
file, is used to serve application level and session level events.
2) Global.asax is compiled to its own assembly – if you
publish the web project from Visual Studio, you can find App_global.asax.dll in
the bin directory, otherwise it will go to c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary
ASP.NET Files\<appname>.
3) Global_asax class inherits from HttpApplication class.
4) The Global.asax file, also known as the ASP.NET
application file, is an optional file that contains code for responding to
application-level events raised by ASP.NET or by HttpModules.
5) The Global.asax file resides in the root directory of
an ASP.NET-based application.
6) The Global.asax file is parsed and dynamically compiled
by ASP.NET.
7) The Global.asax file itself is configured so that any
direct URL request for it is automatically rejected; external users cannot
download or view the code written within it.
8) The Global.asax file does not need recompilation if no
changes have been made to it. There can be only one Global.asax file per
application and it should be located in the application's root directory only.
9) The Global.asax contains two types of events those are:
a) Events which are fired for every request:
Application_BeginRequest(), Application_AuthenticateRequest(), Application_AuthorizeRequest(),
etc.
b) Events which are not fired for every request:
Application_Start(), Session_Start(), Application_Error(), Application_End(),
Session_End(), Application_Disposed().
10) The Global.asax file is optional. If you do not define
the file, the ASP.NET page framework assumes that you have not defined any
application or session event handlers.
Q) Difference between
string.Empty, “” and null?
1) String.empty is initialised to “” at runtime. We cannot use in switch but we
can use in if.
Example: value = String.Empty; if (value==””){ }
2) String.Empty does not create object while “” creates an
object.
3) Null means absence of data. Null is not a value, it is
a state indicating that object value is unknown or non-existent.
Q) Difference between user
control and custom control?
1) Custom Control Inherits from WebControl to achieve some
extra functionality. These are classes.User Control is collection or grouping
of WebControls. It is similar to aspx page and is used to place common markup
code in a common file.
2) Custom controls provide more atomic control (i.e custom
controls are more flexible) as compared to user controls.
3) Custom controls are dlls which are precompiled but user
controls need to be compiled every time with the aspx page in which it has been
embedded.
4) If there is need of application specific control, then
user controls will serve the purpose but when we need redistributable controls,
custom controls are the best ones.
5) Custom control derives from control class(System.Web.UI.Control)While
User control derives from user control (System.Web.UI.UserControl).
6) Has full textbox support and can't be added to the
toolbox.
Q What is enum?
Enumeration is a user defined integer type that allows us
to give user friendly names. It is generally used when we have limited number
of numeric choices and want to convey these choices with user friendly names.It
makes our code cleaner, easy to maintain and easy to use as Visual studio
provides its intellisense. Example:
Enum day
{
Sunday, Monday, Tuesday
}
In the above example, Sunday is 0, Monday is 1 and Tuesday
is 2.
By default C# enum member is set 0 and each of the
subsequent member is incremented by one. The type of an enumerator is int by
default. However, we can declare explicitly a base type for each C# enum. The
valid base types are: Byte, sbyte, short, ushort, int, uint, long, ulong.
Example:
enum shape : long
{
Circle,
Square =100,
Triangle
}
Note:
1) We can’t declare char as an underlying data type for
enum objects because char stores Unicode characters, but enum objects data type
can only be number.
2) enum can’t be derived from any other type except that
of type byte, sbyte, short, ushort,int, uint, long, or ulong.
3) By default, enum
is a sealed class and therefore sticks to all the rules that a sealed class
follows, so no class can derive from enum, i.e., a sealed type.
4)
Q) New keyword
There are two uses of new keyword:
1) For creating object
A obj = new A();
2) For hiding the base class
method from derived class simply declare the derived class method with new
keyword.
Example:
Class A
{
public
void Test( {Console.WriteLine(“Class A”)});
}
Class B:A
{
//Hidiing
the method of A
public
new void Test( {Console.WriteLine(“Class B”)});
}
Class program
{
static
void main(string[] args)
{
A
ObjA = new A();
B
ObjB = new B();
ObjA.Test();
//output-> Class A
ObjB.Test(); //output-> Class B
ObjA = new B();
ObjA.Test(); //output-> Class A
}
}
Note: If you will not use new keyword, compiler will show warning.
Q) Override keyword
A method can be overridden by declaring it virtual in
parent class i.e in order for an instance of a derived class to completely take
over a class member from a base class, the base class has to declare that
member as virtual. This is accomplished by adding the virtual keyword before
the return type of the member. A derived class then has the option of using the
override keyword, instead of new, to replace the base class implementation with
its own. For example:
C#
public class BaseClass
{
public virtual
void DoWork() { }
public virtual
int WorkProperty
{
get { return
0; }
}
}
public class DerivedClass : BaseClass
{
public override
void DoWork() { }
public override
int WorkProperty
{
get { return
0; }
}
}
Q) Virtual keyword
Fields cannot be virtual; only methods, properties, events
and indexers can be virtual. When a derived class overrides a virtual member,
that member is called even when an instance of that class is being accessed as
an instance of the base class.
Q) Summary about New, override,
virtual?
1. The virtual keyword
is used to modify a method, property, indexer, or event declared in the base
class and allow it to be overridden in the derived class.
2. The override keyword
is used to extend or modify a virtual/abstract method, property, indexer, or
event of base class into derived class.
3 The new keyword is
used to hide a method, property, indexer, or event of base class into derived
class.
Q) What is the difference between
Server.Transfer and Response.Redirect?
1) Response.Redirect changes the url in the browser while
Server.Transfer retains the original url in the browser. It just replaces the
contents of the previous page with the new one.
2) Response.Redirect used for both aspx and html pages.
Server.Transfer used only for aspx page.
3) Response.Redirect involves a round trip to the server
while Server.Transfer conserve server resources by avoiding the round trip. It
just changes the focus of the web server to a different page and transfers the
page processing to a different page.
4) Response.Redirect can be used to redirect a user to an
external website. Server.Transfer used only for sites running on the same
server. It cannot be used to redirect the user to a page running on a different
server.
Q) What is the difference between
Response.redirect and Response.Redirectpermanent and server.transfer?
The Response.Redirect generates Response code as 302
whereas RedirectParmanent returns 301. Server. transfer generates response as
200.
1. Response.Redirect() : Search Engine will take this
redirection as Temporary(Status 301) and always keep Page1 in its cache.
2. Response.RedirectParmanent() : Search Engine will take
this a permanent redirection(Status 302) and will remove Page1 from its
database and include Page2 for better performance on search.
3. Server.Transfer() : Search Engine will be unaware of
any redirection been took place (Status 200) and will keep Page1 to its
database. It will think Page1 is producing the output response of Page2.
When
to use:
Response.Redirect is perfect when your page is temporarily
changed and will again be reverted to original within a short span of time.
Response.RedirectParmanent() when you are thinking of
deleting the original page totally after the search engines changes its
database.
Server.Transfer() when you are thinking of keeping the
page for ever, and to let search engine unaware of this redirection.
Q) What is the difference between
HiddenField and ViewState?
1) The HiddenField control is used to store a value that
needs to be persisted across posts to the server. Normally view state is used
to maintain the state of a Web Form page.
2) ViewState stores the 64 bit encrypted value but Hidden
field does not do any encryption.
3) Hidden field is used to store small amount of data as
compared to viewstate.
4) ViewState internally uses hidden field. It is managed
by ASP.NET Engine and is encrypted by default.
Q) Explain Page Life Cycle.
(1) PreInit, (2) Init, (3) InitComplete, (4) PreLoad, (5)
Load, (6) ControlEvents, (7) LoadComplete, (8) PreRender, (9)
PreRenderComplete, (10) SaveStateComplete, (11) RenderComplete, (12) Unload.
PreInit:
1) Check for the IsPostBack property to determine whether
this is the first time the page is being processed.
2) Create or recreate dynamic controls.
3) Set master page dynamically.
4) Set the Theme property dynamically.
5) Read or set profile property values.
If Request is postback:
1) The values of the controls have not yet been restored
from view state.
2) If you set control property at this stage, its value
might be overwritten in the next event.
Init:
1) The Init event of the individual controls occurs first,
later the Init event of the Page takes place.
2) This event is used to initialize control properties.
InitComplete:
1) Tracking of the ViewState is turned on in this event.
2) Any changes made to the ViewState in this event are
persisted even after the next postback.
PreLoad:
This event processes the postback data that is included
with the request.
Load:
In this event the Page object calls the OnLoad method on
the Page object itself, later the OnLoad method of the controls is called. Thus
Load event of the individual controls occurs after the Load event of the page.
ControlEvents:
1) This event is used to handle specific control events
such as a Button control’s Click event or a TextBox control’s TextChanged
event.
2) In case of postback, if the page contains validator
controls, the Page.IsValid property and the validation of the controls takes
place before the firing of individual control events.
LoadComplete:
1) This event occurs after the event handling stage.
2) This event is used for tasks such as loading all other
controls on the page.
PreRender:
1) In this event the PreRender event of the page is called
first and later for the child control.
2) Usage:This method is used to make final changes to the
controls on the page like assigning the DataSourceId and calling the DataBind
method.
PreRenderComplete:
1) This event is raised after each control's PreRender
property is completed.
SaveStateComplete:
1) This is raised after the control state and view state
have been saved for the page and for all controls.
RenderComplete:
1) The page object calls this method on each control which
is present on the page.
2) This method writes the control’s markup to send it to
the browser.
Unload:
1) This event is raised for each control and then for the
Page object.
2) Use this event in controls for final cleanup work, such
as closing open database connections, closing open files, etc.
Q) What is the difference between
Response.Write() and Response.Output.Write()?
Response.write() just writes/displays the text or string
on the web page.
E.g: Response.Write("hi");// Output will be
simply hi.
Response.output.write() formats the string in the format
specified before displaying it on the web page.
E.g: Response.output.write("Hi I am {0}. I am {1} yrs
old.","Shubham","28")
Q) Difference between Stack and
heap.
When you declare a variable in a .Net application, it allocates
some chunk of memory in the RAM. This memory has three things: the name of the
variable, the data type of the variable, and the value of the variable. There
are two types of memory allocation: stack and heap. Depending on the data type,
the memory is allocated.
Stack: The stack is
responsible for keeping track of the running memory needed in your application.
In stack memory allocation and deallocation is done using LIFO. In other words
memory is allocated and deallocated at only one end of memory i.e. top of the
stack. Reference pointers are allocated on stack. Stack memory will be
de-allocated when the variable goes out of scope after execution of the method
in which it is present.
Heap: Heap is a pile of objects which can be reached at any point
of time. Heap is used for dynamic memory allocation. If the requirement is of
dynamic memory, it’s allocated on the heap or else it goes on a stack. Heap
memory will be de-allocated by the garbage collector.
Example: In order to understand stack and heap, let’s understand
what actually happens in the below code internally. ‘Heap’ does not track
running memory.
Public void Method1 ()
{
//Line 1
int i=4;
//Line 2
int y=2;
//Line 3
Class obj = new Class ();
}
Explanation of above Code:
1) When Line1 is executed, the compiler allocates memory
for the variable i in the stack. (The stack is responsible for keeping track of
the running memory needed in your application.)
2) When Line2 is executed, the compiler stacks this memory
location on top of the first memory location. (You can think about stack as a
series of compartments or boxes put on top of each other.)
3) When Line3 is executed, it creates a pointer on the
stack and the actual object is stored on heap.
4) Now finally when the execution control passes the end
control, it clears all the memory variables
Q) Why can’t we allocate
everything on just one memory type (why two memories- stack and heap)?
If you look closely at “int i = 0”, it holds single value
but object data types are complex.
Object types hold reference to multiple values and each one of these
values must be stored in memory. Object types need dynamic memory while
primitive ones need static type memory.
Q) Can we share session value between
two Asp.Net applications?
Yes, If we will store session value in Sql server then we
can retrieve this value in any other application.
Q) What is overhead?
Overhead is a combination of excess or indirect
computation time, memory, bandwidth or other resources that are required to
attain a particular goal.
Q) Difference between ToString()
and Convert.ToString().
Calling ToString() on
an object presumes that the object is not null (since an object needs to exist
to call an instance method on it). Convert.ToString()
doesn't need to presume the object is not null (as it is a static method on the
Convert class), but instead will return String.Empty if it is null.
Q) Why we need to write the the
name of the function/method in derived class as already we wrote in abstract
class?
BY writing in abstract class,
(1) We are providing abstraction (if some new developer
analyzes the code then it will be very easy to identify what are the main
methods involved).
(2) For naming convention also.
Q) What is the difference between
bool and Boolean? Similarly difference between string and String?
Bool is an alias for System.Boolean.
Same reason for others like string and String (string is
an alias for System. String, int is an alias for System.Int32).
Link: http://msdn.microsoft.com/en-us/library/c8f5xwh7(v=vs.80).aspx
Check list of aliases in c#:
http://msdn.microsoft.com/en-us/library/ya5y69ds%28VS.80%29.aspx
Q) Why C# is a strogly typed
language?
Before a value can be stored in a variable, the type of
the variable must be declared.
Q) Conversions?
1) Implicit conversion:
No special syntax is required because the conversion type is safe and no date
will be lost. Examples include conversions from smaller to larger integral
types, and conversions from derived classes to base classes.
2) Explicit conversion:
Explicit conversion require a cast operator. Casting is required when
information might be lost in the conversion, or when the conversion might not
succeed for other reasons. Typical examples include numeric conversion to a
type that has less precision or a smaller range, and conversion of a base class
instance to a derived class.Using explicit conversions we are actually letting
the compiler know that we know there is possible information loss but still we
need to make this conversion. So if we need to convert a long type to an
integer type we need to cast it explicitly.
3) User defined conversions:
User defined conversions are performed by special methods that you can define
to enable implicit and explicit conversions between custom types that do-not
have a base class-derived class relationship.
4) Conversion with helper
classes: To convert between non-compatible types, such as integers and
System.Datetime objects, or hexadecimal strings and byte arrays, we can use the
System.BitConverter class, the System.Convert class and the parse methods of
the built-in numeric types, such as Int32.Parse.
Q) What is SqlDataAdapter?
A SqlDataAdapter is a bridge between the data source and
the dataset. Select, Update, Insert or Delete operations can be performed by
SqlDataAdapter. A SqlDataAdapter contains a connection object and command
object. It operates in disconnected mode and opens or closes the connection
automatically while reading or writing to a database.
Example:
SqlConnection
con = new SqlConnection(constring);
SqlCommand
cmd = new SqlCommand(con);
SqlDataAdapter
dataAdapt = new SqlDataAdapter(cmd);
Datatable
dt = new datatable;
dataAdapt.Fill(dt);
Q) What is non-generic
(Systems.Collections)?
The System.Collections namespace contains classes and
interfaces that define various collection of objects such as lists, queues, bit
arrays, hashtables, and dictionaries., etc. Classes such as ArrayList,
BitArray, Comparer, DictionaryBase, etc. interfaces such as ICollection,
IComparer, IEnumerable, IEnumerator, IDictionary, etc.
Q) What is generic
(Systems.Collections.Generic)?
The System.Collections.Generic namespace contains
interfaces and classes that define generic collections which allow users to
create strongly typed collections that provide better type safety and performance
than non-generic collections. Classes such as Comparer<T>,
Dictionary<T>, List<T>. Interfaces such as ICollections<T>,
IList<T> etc. Note: T defines the type.
Q) Difference between Generic and
Non-Generic?
The main difference between generic and non-generic
collections is that generic provides better type safety and performance issues
than non-generic.
Example: In List<T>, type will be declared in place
of T at compile time only. In List, type is not declared. So, we can add object
of any type. Hence, lot of boxing has to be done because it converts all types
into one type before doing any operation.
Q) Uses of New keyword?
1) To create object. ClassA objA = new ClassA();
2) To hide the base class method in derived class
Q) How to read XML document?
Step 1: Dataset ds = new dataset(); //Declare a dataset.
Step 2: ds.ReadXml(<path of the XML file>); or
ds.ReadXml(ioStream);
Q) What is the difference between
new and override?
1) New hides the base class method but through override we
can also extend the base class method.
Q) How can we override base class
method?
Base class method must be used with abstract or virtual or
override modifier. Then only we can override in derived class.
Q) How modifiers can be added in
methods?
Modifiers can be added before or after access specifiers.
Q) Can we declare abstract
methods in non-abstract class?
No. We can declare abstract methods only in abstract
class.
Q) Can we declare non-abstract
methods in abstract class?
Yes. We can declare non-abstract as well as abstract
methods in abstract classes.
Q) Difference between virtual and
abstract?
Virtual method
needs body part but abstract may or may no have body part.
Q) Connection pooling.
What is connection pooling?
A connection pool is a cache of database connections
maintained so that the connections can be reused when future requests to the
database are required.
Why connection pooling?
Connecting to a database server typically consists of
several time-consuming steps. A physical channel such as a socket or a named
pipe must be established, the initial handshake with the server must occur, the
connection string information must be parsed, the connection must be
authenticated by the server, checks must be run for enlisting in the current
transaction, and so on.
In practice, most applications use only one or a few
different configurations for connections. This means that during application
execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses
an optimization technique called connection
pooling. If all the
connections are being used, a new connection is made and is added to the pool.
Connection pooling also cuts down on the amount of time a user must wait to
establish a connection to the database.
How connection pooling works?
The pooler maintains ownership of the physical connection.
It manages connections by keeping alive a set of active connections for each
given configuration. Whenever a user calls OPEN on a connection, the pooler
looks for an available connection in the pool. If a pooled connection is
available, it returns it to the caller instead of opening a new connection.
When the application calls CLOSE on the connection, the pooler returns it to
the pooled set of connections instead of closing it. Once the connection is
returned to the pool, it is ready to be used on the next OPEN call.
Some More information about Connection
Pooling:
1) By default, a connection string is enabled with
connection pooling.
2) By default, the maximum number of pools is 100, minimum
is 0.
3) If the connection string is different, new pool will be
created.
Q) There are 10000 records. I
want to display 5000 records in one gridview and 5000 records in another grid
view. What is the process?
SqlConnection con = new SqlConnection (connectionString);
Query1 = “SELECT TOP 5000 * FROM Tbl ORDER BY ID”;
Query2 =” SELECT TOP 5000 * FROM Tbl ORDER BY ID DESC”;
con.Open ();
SqlDataAdapter da1 = new SqlDataAdapter (Query1, con);
SqlDataAdapter da2 = new SqlDataAdapter (Query2, con);
Dataset ds = new Dataset ();
da1.Fill (ds,”dt1”);
da2.Fill (ds,”dt2”);
Grv1.DataSource = ds. Tables [“dt1”];
Grv2.DataSource = ds. Tables [“dt2”];
Grv1.DataBind ();
Grv2.DataBind ();
Q) Garbage Collection.
Advantage of Garbage Collector
1. Allow us to develop an application without having worry
to free memory.
2. Allocates memory for objects efficiently on the managed
heap.
3. Reclaims the memory for no longer used objects and
keeps the free memory for future allocations.
4. Provides memory safety by making sure that an object
cannot use the content of another object.
http://www.dotnet-tricks.com/Tutorial/netframework/0L3P131012-.Net-Garbage-Collection-in-depth.html
Key points about Garbage Collector
1. All objects in the heap are allocated from one
contiguous range of memory address and heap is divided into generations so that
it is easy to eliminate the garbage objects by looking at only a small fraction
of the heap.
2. Gen 0 and Gen 1 occupy a single segment known as the
ephemeral segment. Gen 2 is a set of further segments and the large object heap
is yet another group of segments.
3. Almost, all objects with-in a generation are of the
same age.
4. The newest objects are created at higher memory address
while oldest memory objects are at lowest memory address within the heap.
5. The allocation pointer for the new objects marks the
boundary between the allocated and free memory.
6. Periodically the heap is compacted by removing the dead
objects and sliding up the live objects towards the lower memory address end of
the heap as shown in above fig.
7. The order of objects (after memory reclaims) in memory
remains the same as they were created.
Q) What is satellite assembly?
A Dot 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
selects to view the application in that language. In general, assemblies should
contain culture-neutral resources. If you want to localize your assembly (for
example use different strings for different locales) you should use satellite
assemblies. You are likely to use them when creating a multilingual (UI) application.
Satellite assemblies provide you with the capability of designing and deploying
your solution to multiple cultures, rather than hard coding strings, bitmaps,
etc., into your main application. You are likely to use them when creating a
multilingual (UI) application. Satellite assemblies provide you with the
capability of designing and deploying your solution to multiple cultures,
rather than hard coding strings, bitmaps, etc., into your main application.
Q) Threading
What is thread: A thread executes code synchronously- a set of
instructions processed by the CPU “first-in-first-out”. This can execute any
kind of code, be it updating of the GUI, processing calculations or waiting for
user input. GUI programs typically rely on two layers:
1) Processing stack, which includes any code or task
executed in the background, and
2) User interface, which is supposed to give the user a
means for instructing the program to execute tasks, and receiving timely
“updates” or indications of progress.
How threading works: A multitasking operation system divides the available
processor time among the processes and threads that need it. A thread is
executed in the given time slice, and then it is suspended and execution starts
for next thread/process in the queue. When the OS switches from one thread to
another, it saves thread context for preempted thread and loads the thread
context for the thread to execute. The length of time slice that is allocated
for a thread depends on the OS, the processor, as also on the priority of the
task itself.
Multithreading: CPU can switch between two or more thread contexts so two
tasks (e.g calculation and GUI update) can be executed in parallel or
asynchronously. For example, a program can
make full use of a multi-core processor by instructing each core to process a
separate task, or a chunk of the whole task. This results in improved
performance.
Advantages:
1) One of the advantages of using the threads is that you
can have multiple activities happening simultaneously.
2) Another advantage is that a developer can make use of
threads to achieve faster computations by doing two different computations in
two threads instead of serially one after the other.
Working with threads: In .NET framework, System.
Threading namespace provides classes and interfaces that enable
multi-threaded programming. This namespace provides:
1) Thread Pool class for managing group of threads,
2) Timer class to enable calling of delegates after a
certain amount of time,
3) A Mutex class for synchronizing mutually exclusive
threads, along with classes for scheduling the threads, sending wait
notifications and deadlock resolutions.
Thread Priority or scheduling threads: Every thread has a thread priority assigned to it.
Threads created within the common language runtime are initially assigned the
priority of ThreadPriority.Normal. Threads created outside the runtime retain
the priority they had before they entered the managed environment. You can get
or set the priority of any thread with the Thread.Priority property.
Thread Safety: When we are working in a multithreaded environment, we
need to maintain that no thread leaves in an invalid state. Thread safety
basically means the member of an object always maintain a valid state when used
concurrently by multiple threads. There are multiple ways of doing it .The
Mutex class or the Monitor classes of the Framework enable this, and more
information on both is available in the Framework SDK documentation. Locking is
essential in threaded programs. It restricts code from being executed by more
than one thread at the same time. The syntax for the lock would be as follows:
Using System;
Using System.Threading;
//define the namespace, class etc.
...
public somemethod (...)
{ ...
lock(this)
{
Console.WriteLine (“Inside the lock
now”);
...
}
}
Example of lock:
class Account
{
decimal balance;
private Object thisLock = new Object();
public void Withdraw(decimal amount)
{
lock (thisLock)
{
if (amount > balance)
{
throw new Exception("Insufficient funds");
}
balance -= amount;
}
}
}
Syntax:
In C#:
Thread objThread = new Thread (new ThreadStart
(className.methodName));
In VB:
Dim objThread as New Thread (Address Of
className.methodName)
Example of threading: Common uses for it include any possibly lengthy
operations such as:
1) Downloading images or information from the Internet. Or
2) Assembling a list of files from various directories. Or
3) Computing CPU-heavy results.
using System;
using System.Threading;
public class ServerClass
{
// The
method that will be called when the thread is started.
public
void Instance Method()
{
Console.WriteLine("You are in
InstranceMethod.Running on Thread A”);
Console.WriteLine("Thread A Going
to Sleep Zzzzzzzz”);
// Pause for a moment to provide a delay
to make threads more apparent.
Thread. Sleep (3000);
Console.WriteLine ("You are Back in
InstanceMethod.Running on Thread A");
}
public
static void StaticMethod()
{
Console.WriteLine("You are in
StaticMethod. Running on Thread B.");
// Pause for a moment to provide a delay
to make threads more apparent.
Console.WriteLine("Thread B Going
to Sleep Zzzzzzzz");
Thread.Sleep(5000);
Console.WriteLine("You are back in
static method. Running on Thread B");
}
}
public class Simple
{
public
static int Main(String[] args)
{
Console.WriteLine ("Thread Simple
Sample");
ServerClass serverObject = new
ServerClass();
// Create the thread object, passing in
the
// serverObject.InstanceMethod method
using a ThreadStart delegate.
Thread InstanceCaller = new
Thread(new
ThreadStart(serverObject.InstanceMethod));
// Start the thread.
InstanceCaller.Start();
Console.WriteLine("The Main()
thread calls this " +
"after starting the new
InstanceCaller thread.");
// Create the thread object, passing in
the
// serverObject.StaticMethod method
using a ThreadStart delegate.
Thread StaticCaller = new Thread(new
ThreadStart(ServerClass.StaticMethod));
// Start the thread.
StaticCaller.Start();
Console.WriteLine("The Main ()
thread calls this " +
"after starting the new
StaticCaller threads.");
return 0;
}
}
Q) Late Binding and Early Binding
Overriding, reflection i.e dynamic types are all late
binding. Overloading is early binding.
Q) Difference between HTTP
request methods: post and get?
GET - Requests data from a specified resource.
POST - Submits data to be processed to a specified resource.
Get Method:
1) GET requests can be cached
1) GET requests remain in the browser history
2) GET requests can be bookmarked
3) GET requests should never be used when dealing with
sensitive data
4) GET requests have length restrictions
5) GET requests should be used only to retrieve data
Post method:
1) POST requests are never cached
2) POST requests do not remain in the browser history
3) POST requests cannot be bookmarked
4) POST requests have no restrictions on data length
Q) What is COM?
COM is used to communicate between two computers which are
on intranet. DCOM is for net.
COM is used by developers to create
reusable software components,
link components together to build applications, and take advantage of Windows
services. COM objects can be created with a variety of programming languages.
Object-oriented languages, such as C++, provide programming mechanisms that
simplify the implementation of COM objects. The family of COM technologies
includes COM+, Distributed COM (DCOM) and ActiveX® Controls. Basically a third
party dll. Scenario like in visual studio- c++ we are using by the reference of
third party dll. This is a com component.
Q) Do the following is method
overloading?
String Method1 ()
{ }
Integer Method2 ()
{ }
No, it will show error. Functions which are to be
overloaded cant return values of different data types. Parameters and data
types for parameters (arguments) can be different but return type should be
same.
Q) Difference between session and
application?
Application
variables are the variables which remain common for the whole application…
Their value can be used across the whole application and they die only when the
application stops or probably when they are killed forcibly. The ideal example
for these kind of variables are site counter… We can find out how many people
accessed a particular site since the time it went live via application
variables and incrementing the same on every session start.
Session variables
are variables which remain common for the whole application but for one
particular user. They also can be used across the whole application. But they
die when a particular user session ends or probably when they are killed
forcibly. The ideal example for this kind of variable are user id. You might
want to show "Welcome Vishal" on every page of your site till vishal
logs off… So in session start you set a variable to "Welcome Vishal"
and kill it on session end.
All these methods
like session start, session end, application start, application end are found
in
global.asax and
that’s the reason global.asax is one for the whole ASP.Net application.
Q) CType
Ctype is used to convert the variable
from one type to another.
Example(1):
dim x as integer
x=10
dim str as string
str=ctype(x,str)
Example(2):
Dim
lblcontent As Label =
CType(Master.FindControl("lblcontent"), Label)
Here master page control lblcontent is
found and its converted to label control using ctype
Q) Optional
Parameter
In VB:
You can specify that a procedure
parameter is optional and no argument has to be supplied for it when the
procedure is called. Optional parameters
are indicated by the Optional keyword in the procedure definition. The
following rules apply:
● Every optional parameter in the procedure
definition must specify a default value.
● The default value for an optional
parameter must be a constant expression.
● Every parameter following an optional
parameter in the procedure definition must also be optional.
Syntax:
Sub sub name(ByVal parameter 1 As data
type 1, Optional ByVal parameter 2 As data type 2 = default value)
Example:
Sub notify(ByVal company As String, Optional ByVal office As String = "QJZ")
If office = "QJZ" Then
Debug.WriteLine("office not supplied -- using Headquarters")
office = "Headquarters"
End If
' Insert code to notify headquarters or specified office.
End Sub
If office = "QJZ" Then
Debug.WriteLine("office not supplied -- using Headquarters")
office = "Headquarters"
End If
' Insert code to notify headquarters or specified office.
End Sub
In C#:
n C# 4.0. Named and optional parameters
are really two distinct features, and allow us to either omit parameters which
have a defined default value, and/or to pass parameters by name rather than
position. Named parameters are passed by name instead of relying on its
position in the parameter list, whereas optional parameters allow us to omit
arguments to members without having to define a specific overload matching.
Q) What is mean
by MSIL?
MSIL or IL stands for Microsoft
Intermediate Language; if you compile managed code, the compiler translates
your source code into Microsoft intermediate language. MSIL is platform
independent language which can be converted to native code while installing
software or at runtime by using Just-in compiler.
Q) What is mean
by CTS?
Common type system defines how types are
declared, used, and managed in the runtime, and is also an important part of
the runtime's support for cross-language integration. CTS is responsible for
defining types that can be used across the .Net Languages. CTS Provides the
data types, values, object types. This helps developers to develop applications
in different languages.
For example, an integer variable in C# is
written as int, whereas in VB.Net it is written as integer. Therefore in .Net
Framework you have single class called System.Int32 to interpret these
variables.
Q) What is mean
by CLS?
Common Language Specification is the
subset of CTS; it is specification that defines the set rules and guidelines
that all supporting language should follow. It integrate in such a way that
programs written in any language can interoperate with one another.
Q) What is mean by JIT?
Just In Time(JIT) compilers which compile
the IL code to native executable code (.exe or .dll) for the specific machine
and OS. JIT are slightly different from traditional compilers as they compile
the IL to native code only when desired e.g., when a function is called, IL of
function's body is converted to native code; just in time of need. If same
function is called next time, the CLR uses the same copy of native code without
re-compiling. As JIT are aware of processor and OS exactly at runtime, they can
optimize the code extremely efficiently resulting in very robust applications.
8. What are
different types of JIT?
Pre-JIT - Pre-JIT compiles complete
source code into native code in a single compilation cycle. This is done at the
time of deployment of the application.
Econo-JIT - Econo-JIT compiles only those
functions that are called at runtime. However, these compiled functions are
removed when they are not required.
Normal-JIT - Normal-JIT compiles only
those functions that are called at runtime and they are stored in cache. If
same function is called next time, the CLR uses the same copy of compiled code
without recompiling.
Q) What are
different type's assemblies?
Private assembly- Private assembly is used within your
application and it is installed at the same time as the application itself. It
will be located in the same directory as the application or subdirectories
thereof.
Shared assembly- Shared assemblies are used by several
application. Shared assembly must have version number and unique name and it is
usually installed in GAC (Global assembly cache). It reduces the need for disk
space and memory space.
Q) What are parts
of assembly manifests?
● Identity - Name, version, culture and
public key
● A list of files - Files belonging to the
assembly, it can have one or more files.
● Lists of referenced assemblies - all
assemblies referenced by the assembly are documented inside the manifest.
● Set of permission requests- these are the
permission needed to run the assembly.
● Exported types - It describes the
structures, class with properties, method and events. It is used to create
instance of the class.
Q) What is portable
executable (PE)?
The file format defining the structure
that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to
allow them to be loaded and executed by Windows. PE is derived from the
Microsoft Common Object File Format (COFF). The EXE and DLL files created using
the .NET Framework obey the PE/COFF formats and also add additional header and
data sections to the files that are only used by the CLR.
Q) How Garbage collector will get memory from
OS?
When execution engine starts, GC will
initialize segment of memory for its operation. GC reserves memory in segment,
each segment is 16MB. When we run out of segments we reserve a new segment. If
a segment of memory is not in use, it will be deleted.
Q) What is mean
by LOH?
LOH-(Large Object Heap). If size of the
object are very high(>64KB) then it will be stored in different segment of
memory called as LOH. GC will treat the large objects differently from small
objects.
Q) What are
situations GC will be called?
1. If user forcefully calls
System.GC.Collect
2. System is in low memory situation
3. Memory allocation exceeds the Generation0
threshold
Q) What is mean by
value type and Reference type?
Value type- Value type stores their value
directly to memory address. Value type's values are allocated on the stack
memory.
Reference type - Reference type stores
the reference to the value's memory address. Reference type values are
allocated on heap memory.
Q) What is mean
by Boxing and Unboxing?
Boxing - Converting value type variable
to reference type is called as boxing
UnBoxing - Converting reference type
variable to value type is called as unboxing
int vType = 35;
object rType;
//Boxing process
rType = vType;
//Unboxing process
vType =(int) rType;
object rType;
//Boxing process
rType = vType;
//Unboxing process
vType =(int) rType;
Q) What is difference between System exception and Application
exception?
All exceptions are derived from the
Exception base class. Where Exception class is derived from the Object class.
Both System and Application exception are derived from exception class but it
has difference between them. System exceptions are thrown by the CLR where as
Application exceptions are thrown by Application.
System Exception
|
Application
Exception
|
System exceptions
are thrown by CLR
|
Application
exceptions are thrown by Application
|
E.g
OutOfMemoryException, NullReferenceException,etc
|
E.g User defined
exception are created to throw application's exception and user defined
exceptions are derived from ApplicationException
|
Q) What is Reflection?
.Net compilers store metadata
information(types defined) about the assemblies inside the assembly itself.
Using this metadata we can load an assembly dynamically (at runtime), get
information about its containing types, instantiate these types and call
methods.
"Reflection" is a mechanism
using which we can load an assembly dynamically and call its method. The
System.Reflection is the root namespace that contains classes to implement the
reflection. The Assembly class is the one which is used to represent the
assembly in .Net environment.
Example:
static void Main(string[] args)
{
// Load an assembly from file
Assembly myAssembly = Assembly.LoadFrom("MyService.dll");
// Get the types contained in the assembly and print their names
Type[] types = myAssembly.GetTypes();
foreach (Type type in types)
{
Console.WriteLine(type.FullName);
//Get the members(methods) present inside each type
foreach (MemberInfo member in type.GetMembers())
{
Console.WriteLine(" "+member.Name);
}
}
Console.ReadLine();
}
{
// Load an assembly from file
Assembly myAssembly = Assembly.LoadFrom("MyService.dll");
// Get the types contained in the assembly and print their names
Type[] types = myAssembly.GetTypes();
foreach (Type type in types)
{
Console.WriteLine(type.FullName);
//Get the members(methods) present inside each type
foreach (MemberInfo member in type.GetMembers())
{
Console.WriteLine(" "+member.Name);
}
}
Console.ReadLine();
}
Q) If we have two
different version of same assembly in GAC how do we make a choice?
using < bindingRedirect > tag in
App.config file
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="AssemblyVersionExample"
publicKeyToken="7c779e284ebe2e8c"
culture="neutral" />
<bindingRedirect oldVersion="1.0.0.20"
newVersion="1.0.0.10"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
37. What is mean
by Dll Hell?
DLL hell means deploying the same DLL in
your application multiple times. In windows application dlls are shared across
multiple application. Suppose when App1 is using MyAssembly.dll and it is
working fine. Suppose I am installing new application App2 which also having
assembly MyAssembly.dll, while installing App2 it will override the old
assembly with new MyAssembly.dll. Now only App2 will function properly where as
App1 which depends on MyAssembly.dll will fail. This is called as Dll hell. It
can be solved by assembly versioning.
Q) How's the DLL
Hell problem solved in .NET?
Assembly versioning allows the
application to specify not only the library it needs to run (which was
available under Win32), but also the version of the assembly.
Q) Can we
override static method?
No, compiler will not allow overriding
the static method.
Q) What are uses
of static class and method?
1. Compiler will not allow creating the
instance of the class
2. Static class also makes the
implementation simpler and faster
3. Cannot inherit a static class since it is
sealed
Q) Can you allow
class to be inherited, but prevent the method from being overridden?
Yes, just leave the class public and make
the method sealed.
Q) Will sealed
class allows inheritance, if not why?
Sealed means it is not inheritable
Q) What are the
advantages of Private constructor?
1. Private constructor will prevent the user
from creating the instance of the class which contains only static members.
2. Private constructor are used for
implementing the singleton pattern
Q) While using
inheritance, derived class constructor will call base class constructor?
Yes, base class constructor will be
called before child class constructor
Q) Overloaded
constructor will call default constructor internally?
No, overload constructor will not call
default constructor
Q) What is
difference between Overrides and Overridable?
Overridable
(VB.Net)/ virtual (C#) is used in parent class to indicate that a method can be overridden. Overrides(VB.Net)/ override(C#) is used
in the child class to indicate that you are overriding a method.
Q) What is
operator overloading?
Operator overloading is used to provide a
custom functionality to existing operators. For Example +,-,* and / operators are
used for mathematical functionality. But we can overload these operators to
perform custom operation on classes or structure.
Example:
To concatenate the two strings we have to
use Concat method
Dim str1, str2, str3 As String
str1 = "Hello"
str2 = "world"
str3 = String.Concat(str1, str2)
str1 = "Hello"
str2 = "world"
str3 = String.Concat(str1, str2)
But .Net provides in build operator overloading
for string we can use ‘+’ operator for concatenating the string value
str3=str1+str2
Similarly we can also implement operator
overloading for classes or structure
Employee3= Employee1 + Employee2
Q) Sealed
alternative in VB?
NotInheritable
Q) Serialization.
Serialization is
the process by which we can save the state of the object by converting the
object into some serial data format, such as XML or
binary format . These data can then be stored in database, files, memory
etc.
In the language of
computer in context of data storage and transmission, serialization is the
process of translating data stuctures or objects into a format that can be
stored in a file or memory buffer, or transmitted across a network connection
link and resurrected in the same or another computer environment.
When you create
an object in .Net Framework application, you dont need to think about how the
data is stored in memory, because .Net Framework takes care of that for you.
However for transmission you need to store it in different format. This
conversion is called serialization. Below is a
simple code of serializing the object.
MyObject objObject = new MyObject();
objObject.Value = 100;
// Serialization using SoapFormatter
SoapFormatter formatter = new SoapFormatter();
Stream objFileStream = new FileStream("c:\\MyFile.xml", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(objFileStream, objObject);
objFileStream.Close();
objObject.Value = 100;
// Serialization using SoapFormatter
SoapFormatter formatter = new SoapFormatter();
Stream objFileStream = new FileStream("c:\\MyFile.xml", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(objFileStream, objObject);
objFileStream.Close();
Desirialization
is the reverse process of serialization. Below is simple
code which shows how to deserialize an object.
//De-Serialization
Stream objNewFileStream = new FileStream("c:\\MyFile.xml", FileMode.Open,
FileAccess.Read, FileShare.Read);
MyObject objObject =(MyObject)formatter.Deserialize(objNewFileStream);
objNewFileStream.Close();
//De-Serialization
Stream objNewFileStream = new FileStream("c:\\MyFile.xml", FileMode.Open,
FileAccess.Read, FileShare.Read);
MyObject objObject =(MyObject)formatter.Deserialize(objNewFileStream);
objNewFileStream.Close();
Q) Array syntax and
initialization.
In
C#:
int[] arr = new
int[10]{8,7,6,5,4,3,2,1};
In
VB.Net:
Dim arr(10) As
Integer ={1,2,3,4,5,6}
Q) Properties
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
// Auto-Impl
Properties for trivial get and set
public double TotalPurchases { get; set; }
public double TotalPurchases { get; set; }
Q) Web Service
The software field is following the way
like this. First functional programming came, then OOPS programming to apply
reusability, extensibility. Then everything was solved but there was need of
communication between different applications. So web service was introduced for
this.
Web service is an application that is designed to
interact directly with other applications over the internet. Web Service is language independent and
Web Services communicate by using standard web protocols and data formats, such
as
1)
HTTP – Hyper Text Transfer Protocol
2)
SOAP – Simple Object Access Protocol
3)
XML – EXtensible Markup Language
Advantages of Web Service: Web Service messages are formatted as
XML, a standard way for communication between two incompatible system. And this
message is sent via HTTP, so that they can reach to any machine on the internet
without being blocked by firewall.
Examples for Web Service:
1) Weather Reporting: You can use Weather
Reporting web service to display weather information in your personal website.
2)
Stock Quote: You can display latest update of Share market with Stock Quote on
your web site.
3)
News Headline: You can display latest news update by using News Headline Web
Service in your website.
In
summary you can any use any web service which is available to use. You can make
your own web service and let others use it. Example you can make Free SMS
Sending Service with footer with your advertisement, so whosoever use this
service indirectly advertise your company. You can apply your ideas in N no. of
ways to take advantage of it.
If web service is created on local host,
its address will be like this:
http://localhost/SampleWebService/Service.asmx
Q) What is SOAP?
SOAP (simple object access protocol) is a
remote function call that invokes method and execute them on Remote machine and
translate the object communication into XML format. In short, SOAP is a way by which method calls are
translated into XML format and sent via HTTP.
Q) What is WSDL?
WSDL stands for Web Service Description
Language, a standard by which a web service can tell clients what messages it
accepts and which results it will return.
WSDL contains every detail regarding
using web service and Method and Properties provided by web service and URLs
from which those methods can be accessed and Data Types used. If we will type
the following in browser, we can see the wsdl for any web service present.
<web service address>?wsdl
Q) What is UDDI?
UDDI (Universal Description Discovery and
Integration) allows you to find web services by connecting to a directory.
Q) What is
Discovery or .Disco Files?
Discovery files are used to group common
services together on a web server. Discovery files .Disco and .VsDisco are XML
based files that contains link in the form of URLs to resources that provides
discovery information for a web service. Disco File contains URL for the WSDL,
URL for the documentation and URL to which SOAP messages should be sent.
Q) Difference
between reflection and dynamic?
1) Both reflection and dynamic are used
when we want to operate on an object during runtime.
2) Reflection is used to inspect
meta-data of an object. It also has the ability to invoke members of an object
on runtime.
3) Dynamic is a keyword which was
introduced in .NET 4.0. It evaluates object calls during runtime. So until the
method calls are made, compiler is least bothered if those methods or
properties etc exist or not.
4) Dynamic uses reflection internally. It
caches the method calls made thus improving performance to a certain extent.
5) Reflection can invoke both public and
private members of an object while dynamic can only invoke public members.
Below is the detail comparison table
which shows in which scenario they are suited.
Reflection
|
Dynamic
|
|
Inspect ( Meta-data)
|
Yes
|
No
|
Invoke Public members
|
Yes
|
Yes
|
Invoke Private members
|
Yes
|
No
|
Caching
|
No
|
Yes
|
Q) DataReader vs DataAdapter vs Dataset
DataReader: DataReader is
used to read the data from database and it is a read and forward only
connection oriented architecture during fetch of data from database. DataReader
is used to iterate through result set that came from server and it will read
one record at a time and hence memory consumption will be less and it will
fetch the data very fast when compared with dataset. Generally we will use
ExecuteReader object to bind data to datareader.
DataSet: DataSet is based
on disconnected orient architecture. It means that there is no need of active
connections during work with datasets and it is a collection of DataTables and
relations between tables. It is used to hold multiple tables with data. You can
select data form tables, create views based on table and ask child rows over
relations. Also DataSet provides you with rich features like saving data as XML
and loading XML data.
DataAdapter: DataAdapter will
acts as a Bridge between DataSet and database. This dataadapter object is used
to read the data from database and bind that data to dataset. Dataadapter is a
disconnected oriented architecture.
Q) Q) Can I overload int32 and int64
parameters?
Yes
void
method1(Int32 a)
{
Console.WriteLine(a.ToString());
}
void
method1(Int64 b)
{
Console.WriteLine(b.ToString());
}
Q) What is protected internal?
How to access the class in another assembly?
Definition: It is an access
specifier in C#. Access is limited to the current assembly or types derived in
other assembly.
How
to Access:
1) Create one project (SomeProject) and inside
it, create one class with public specifier (e.g public class A).
2) Create a method with access specifier as
protected internal () inside this class.
3) Now create another project (AnotherProject)
and take reference of the project (SomeProject)
already created.
already created.
4) Create a class and inherit the class present
in the referenced assembly. Now we can call
the method present in the parent class directly. No need to create object of
the parent class.
the method present in the parent class directly. No need to create object of
the parent class.
Q) You have a big page. So you will divide into two pages. In first
page you have next button. In second page you have previous button. How you
will persist the data of first page when you click on previous button of second
page.
Ans: Through Session as there are two different aspx pages.
Q) What is background garbage collection?
In background
garbage collection, ephemeral generations (0 and 1) are collected as needed
while the collection of generation 2 is in progress. There is no setting for
background garbage collection; it is automatically enabled with concurrent
garbage collection. Background garbage collection is a replacement for
concurrent garbage collection. As with concurrent garbage collection,
background garbage collection is performed on a dedicated thread and is
applicable only to generation 2 collections.
NOTE:
1) Background
garbage collection is available only in the .NET Framework 4 and later
versions.
2) Background
garbage collection is not currently available for server garbage collection.
Q) What is App domain?
Operating and
runtime environments typically provide some form of isolation between
applications. For example, Windows uses process to isolate applications. This
isolation is necessary to ensure that code running in one application cannot
adversely affect, other unrelated applications.
Definition of
AppDomain: An AppDomain provides a layer of isolation within a process.
Everything you usually think of as "per program" (static variables
etc) is actually per-AppDomain. This is useful for:
1) Plugins (you can unload an AppDomain,
but not an assembly within an AppDomain).
2) Security (you can run a set of code with
specific trust levels).
3) Isolation (you can run different versions
of assemblies etc).
Why
we need AppDomain?
Application
domains provide a flexible and secure method of isolating running applications.
Application domains are usually created and manipulated by run-time hosts. Occasionally, you may want your application to
programmatically interact with your application domains, for example, to unload
a component without having to stop your application from running.
Example: In IIS
some web application is running and after some time due to some bug web
application crashes, hence IIS should also crash. Hence while programming IIS
we can use AppDomain for running web applications and when it crashes, it will
unload this specific AppDomain while saving the IIS from crashing.
Real
time Scenario:
You are writing a
real-time system that processes data received from instruments (e.g. various
blood analyzers). Some of the processing steps are done by various libraries
written by various companies and could fail because a type of instrument is
malfunctioning, a bug in the code, etc. You could use an application domain to
isolate 3rd party processing failures, and simply unload problematic
processing’s when they happen, leaving the core of the system to continue
functioning and process data.
Application
domains have the following properties:
1) An assembly must be loaded into an
application domain before it can be executed.
2) Faults in one application domain cannot
affect other code running in another application domain.
3) Individual applications can be stopped
and code unloaded without stopping the entire process. You cannot unload
individual assemblies or types, only entire application domains.
Code:
//Create
an application Domain:
System. AppDomain newDomain =
System.AppDomain.CreateDomain ("NewApplicationDomain");
//Load
and Execute an assembly:
newDomain.ExecuteAssembly(@"path of exe file");
//Unload
the application domain:
System.AppDomain.Unload(newDomain);
Links:
1) http://liviutrifoi.wordpress.com/tag/c-appdomain-tutorial/
2) http://msdn.microsoft.com/en-us/library/ms173139(v=vs.80).aspx
Q) Validation Controls
All the
validation controls inherit from the base class BaseValidator, which is part of
the class library namespace System.Web.UI.WebControls.
1)
Required Field Validator
<asp:RequiredFieldValidator
id="validTxtName runat="server"
controlToValidate="txtName" errorMessage="Name must be entered" display="static"></asp:RequiredFieldValidator>
controlToValidate="txtName" errorMessage="Name must be entered" display="static"></asp:RequiredFieldValidator>
2)
Regular Expression Validator
<asp:RegularExpressionValidator
id="regvH"
runat="server" display="static"
controlToValidate="txtH" errorMessage="Hours must be 1-3 digits
only"
validationExpression="\d{1,3}"> </asp:RegularExpressionValidator>
validationExpression="\d{1,3}"> </asp:RegularExpressionValidator>
3)
Compare Validator
<asp:CompareValidator
id="comvR" runat="server" display="static"
controlToValidate="txtR" errorMessage="Rate must be numeric"
type="Double" operator="DataTypeCheck"></asp:CompareValidator>
controlToValidate="txtR" errorMessage="Rate must be numeric"
type="Double" operator="DataTypeCheck"></asp:CompareValidator>
4) Range Validator
<asp:RangeValidator
id="ranvDependents" runat="server"
display="static" controlToValidate="txtDependents" errorMessage="Must be from 0 to 10"
type="Integer" minimumValue=0 maximumValue=10> </asp:RangeValidator>
type="Integer" minimumValue=0 maximumValue=10> </asp:RangeValidator>
5)
Custom validator
<asp:CustomValidator
id="cusvDeptNum" runat="server" display="static"
controlToValidate="txtDeptNum"
onServerValidate="validateDeptNum"
errorMessage="Must be in multiples of 10" > </asp:CustomValidator>
errorMessage="Must be in multiples of 10" > </asp:CustomValidator>
6)
Validation Summary
<asp:ValidationSummary
id="valSummary" runat="server" headerText="Please correct the following
errors" display="static"
showSummary= "True" />
Q) Deadlock
A deadlock occurs
when two or more tasks permanently block each other by each task having a lock
on resource which the other tasks are trying to lock. The following graph
presents a high level of a deadlock state where:
1) Task
T1 has a lock on resource R1 (indicated by the arrow from R1 to T1) and
has requested a lock on resource R2 (indicated by the arrow from T1 to R2)
2) Task T2 has a lock on resource R2
(indicated by the arrow R2 to T2) and has requested a lock on resource R1
(indicated by the arrow from T2 to R1)
3) Because neither task can continue until a
resource is available and neither resource can be released until a task
continues, a deadlock state exists.
Example:
static object
object1 = new object();
static object
object2 = new object();
public static
void ObliviousFunction()
{
lock
(object1)
{
Thread.Sleep(1000); // Wait for the
blind to lead
lock
(object2)
{
}
}
}
public static
void BlindFunction()
{
lock
(object2)
{
Thread.Sleep(1000); // Wait for
oblivion
lock (object1)
{
}
}
}
public static
void Main()
{
Thread thread1 = new
Thread((ThreadStart)ObliviousFunction);
Thread therad2 = new
Thread((ThreadStart)BlindFunction);
thread1.Start();
thread2.Start();
while (true)
{
//
Stare at the two threads in deadlock.
}
}
Solution
:
The simplest way
to avoid deadlock is to use a timeout value .
You can use the
Monitor class (system.Threading.Monitor) to set a timeout during acquiring a
lock.
Ex.
in C#
if(Monitor.TryEnter(this, 500))
{
// critical section
}
catch (Exceprion ex)
{
}
finally
{
Monitor.Exit();
}
Here the timeout
is 500 milliseconds .
If the lock can't
be acquired, after 500 miliseconds, timeout occurs and the code exit the
Monitor block.
Q) How to convert datatable or dataset to datareader?
Datatable dt;
DataTableReader
reader = dt.CreateDataReader();
Q) Can we extend String class?
No. because it is
sealed.
Q) ToString()
It belongs to
System and not to System.String. It is overriddable because it is defined as
public virtual
string ToString(){}.
Q) Difference between hashtable and dictionary?
1) Hashtable is
non generic whether dictionary is generic i.e. dictionary can be used with any
data type.
2) Hashtable is
slower than dictionary because it requires boxing and unboxing.
3) Hashtable
returns null if we try to find a key which does not exist but dictionary
returns error
If we try to find
a key which does not exist.
4) All the
members in a hashtable are thread safe. In dictionary only public static
members are thread safe.
5)
System.Collections is the namespace for Hashtable and
System.Collections.Generic is the namespace for Dictionary.
6) Syntax:
HashTable: HashTable
objHash = new HashTable ();
Dictionary:
Dictionary<Tkey, TValue> objDict = new Dictionary<TKey, TValue> ();
Q) Difference between ArrayList and List?
1)
“System.Collections” is the namespace for ArrayList and
“System.Collections.Generic" is the namespace for List<T>.
2) By using both the ArrayList and Generic List
we can store any type of objects. Consider that you are intended to store only
the integer values. In this case when we use ArrayList, we can store any type
of objects (i.e., Integer, String or some custom objects).
Example:
ArrayList
objarList=new ArrayList ();
objarList. Add
(123);
objarList. Add
("senthil"); // will compile but throw runtime error.
It won't throw any compile time error. It will
throw only run time error when we iterate values in the array list by using for
each. But when we use the Generic List, we can restrict in the compile time
itself. If you are intended to store only integer values, it will allow storing
only integer values. If you try to store any other value other than integer,
then it will throw compile time error.
List<int>
objList=new List<int> ();
objList. Add
(123);
objList. Add
("senthil") // Will result in compile time error.
3) Whenever you
are adding the objects in the ArrayList, at that time boxing will happen.
Whenever you are accessing the objects from the ArrayList, at that time
unboxing will happen. So it will hurt the performance. But in case of Generic
List there will not be any Boxing or UnBoxing problem and also it will provide
the better type safety.
Q) Difference between array and array list.
1) Arrays are strongly typed whereas Array-Lists are not
strongly typed.
2) Elements in Arrays have to be of same data type (int,
string, double, char, bool…). Elements in Array-List can have a combination of
combined data types or single data type. Note: If Array-List has combined data
types then type cast is must.
3) Arrays are fixed specified length size therefore they
cannot be resized dynamically during runtime. Array-List can resize dynamically
during runtime.
Q) Class A inherits Class B and Class B inherits Class C ?
It is possible,
class C can access all the properties and methods present in Class A and Class
B.
Q) What is a private constructor?
A private constructor is a special instance constructor.
It is generally used in classes that contain static members only.
1) A class containing private constructor cannot be
inherited.
2) A class containing private constructor cannot be
instantiated.
3) Many times we do not want to create instances of
certain classes, common routine classes.
Q) What is c#?
1) C# (pronounced "C sharp") is a simple,
modern, object-oriented, and type-safe programming language.
Q) What are three different types of comment in c#?
1) Single line \\
2) Mutli line \*
*\
3) Page/Xml
Comments \\\
Q) What are the modifiers in c#?
1) Abstract
2) Sealed
3) Virtual
4) Const
5) Event
6) Extern
7) Override
8) Readonly
9) Static
10) New
Q) Differences between singleton pattern and static implementations:
1) we can
implement interface with Singleton class but not with Static class.
2) Singleton
object stores in Heap but, static object stores in stack
3) Static class
provides better performance than Singleton pattern, because static methods are
bonded on compile time.
4) When you need
a class with full OO capability , chose Singleton, while if you just need to
store bunch of static methods together, than use static class.
Q) What is the use of enumerated data type?
An enumerated
data type is another user defined type which provides a way for attaching names
to numbers thereby increasing comprehensibility of the code. The enum keyword
automatically enumerates a list of words by assigning them values 0, 1, 2, and
so on.
Q) What are the types of access modifiers?
Public, Private,
Protected, Internal, Protected Internal
Q) Difference between IEnumerable vs IQueryable in .NET C#.
Difference: The difference
is that IQueryable<T> is the interface that allows LINQ-to-SQL
(LINQ.-to-anything really) to work. So if you further refine your query on an
IQueryable<T>, that query will be executed in the database, if possible.
For the
IEnumerable<T> case, it will be LINQ-to-object, meaning that all objects
matching the original query will have to be loaded into memory from the
database. And then filter it as per your requirement.
Example:
IEnumerable<Student>
students = myModel.GetStudent ();
Var
studentsOver25 = students. Where (p => p.ID >= 25);
What happens here
is the database loads all of the students, and passes them across to your
program. Your program then filters the data. In essence, the database does a
“SELECT * FROM Student”, and returns EVERY Student to you. And then put a filter
of ID >= 25. This will load all records of student to memory and then put
filter on it.
IQueryable<Student>
students = myModel.GetStudent ();
Var
studentsOver25 = students. Where (p => p.ID >= 25);
Code looks quite
same but difference in execution database does a “SELECT * FROM Student where
ID >= 25” from a performance standpoint it will return only record with ID
> 25 .
Such an ideal piece of blog.Thanks for sharing
ReplyDelete.Net Online Course Hyderabad