Differences in .NET

What is the difference between Abstract Class and Interface?

Abstract Class:

a) An abstract class is a special kind of class that cannot be instantiated.
b) It allows the other classes to inherit from it but cannot be instantiated.
c) It is used to carry the same hierarchy or standards for all the subclasses.


a) An interface is not a class,but it is an entity and has no implementation.
b) It has only the definition of the methods without the body.


1) A class may inherit several interfaces, but inherit only one abstract class.
2) An abstract class cn provide complete code, but interface provides just the signature.
3) An abstract class can contain access modifiers for the subs, functions, properties, but an interface cannot.
4) An abstract class defines the core identity of a class, but interfaces are used to define the peripheral abilities of a class.
5) An abstract class is fast whereas the interfaces requires more time to find the actual method in the corresponding classes.
6) If we add a new method to an abstract class, there we can provide the default implementation and therefore all the existing code might work properly whereas in interface, we have to track down all the implementations of the interface and define implementation for the new method.
7) In Interface, we cannot define the fields whereas in an Abstract class, we can define the fields and constants.

Abstract Classes: Classes which cannot be instantiated. This means one cannot make a object of this class or in other way cannot create object by saying ClassAbs abs = new ClassAbs(); where ClassAbs is abstract class.
Abstract classes contains have one or more abstarct methods, ie method body only no implementation.
Interfaces: These are same as abstract classes only difference is we can only define method definition and no implementation.
When to use wot depends on various reasons. One being design choice.
One reason for using abstarct classes is we can code common
functionality and force our developer to use it. I can have a complete
class but I can still mark the class as abstract.
Developing by interface helps in object based communication.
Difference between Abstract and virtual method?

An Abstract method must be override in child classes where as virtual method is not compulsory to override.
An abstract method doesn’t have implementation detail where as virtual method has it.
only abstract class can haveabstract method, any class can have virtual method

as you know virtual method either be public or be protected.
in both case if don’t override it, default implementation that was written in base will work for derived also.
you need not to type case derived class object with base class objects. you can call that method from derived class’s objectalso.

Abstract method are those which are not defined. Means if your method doesnt have its body it is abstract.

On the other hand, if you have already defined the body and want the classes that derives it can override its member, if they wish, you define it as virtual.

Difference between class and struct in C# .Net?

1. Classes are reference types and structs are value types.
Since classes are reference type, a class variable can be assigned null.But we cannot assign null to a struct variable, since structs are value type.
2. When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it gets created on the stack.
3. You will always be dealing with reference to an object ( instance ) of a class. But you will not be dealing with references to an instance of a struct ( but dealing directly with them ).
4. When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference.
5. You cannot have instance Field initializers in structs.But classes can have
class MyClass
int myVar =10; // no syntax error.
public void MyFun( )
// statements
struct MyStruct
int myVar = 10; // syntax error.
public void MyFun( )
// statements
6. Classes can have explicit parameterless constructors. But structs cannot have
7. Classes must be instantiated using the new operator. But structs can be
8. Classes support inheritance.But there is no inheritance for structs.
( structs don’t support inheritance polymorphism )
9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.11. A class is permitted to declare a destructor.But a struct is not
12. classes are used for complex and large set data. structs are simple to use.


What is the difference between UNION and UNION ALL?

UNION command selects distinct and related information from two tables. On the other hand, UNION ALL selects all the values from both the tables.


Table employee:-

Employee name Salary
John 1000
Mike 2000
Peter 2500
Micheal 1000

Table appraisal:-

Employee name Appraisal amount
Mike 450
Lisa 1000
Mark 230
Peter 400

SELECT Employee_name FROM employee
SELECT Employee_name FROM appraisal


Difference between dataset and data table?

A DataSet holds one or more DataTables.

Example 1:

DataTable dt = new DataTable();
DataSet ds = new DataSet();

Example 2:

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataSet ds = new DataSet();

In case not, then:
DataTable = A table with rows and columns
DataSet = A set with datatables. Can hold one or more Datatables in it. A container of datatables. Not just it, in Dataset you can have relations between tables too.


A DataTable is an in-memory representation of a single database table which has collection of rows and columns

2.Number of rows retrieved at a time:
DataTable fetches only one TableRow at a time

3.Provision of DataRelation Objects:
As DataTable is a single database table, so there is no DataRelation object in it.

4.Enforcing Data Integrity:
In DataTable, there is no UniqueConstraint and ForeignKeyConstraint objects available.

5.DataSource can be Serialized or Not:
In DataTable, DataSource cannot be serialized.

A DataSet is an in-memory representation of a database-like structure which has collection of DataTables.

2.Number of rows retrieved at a time:
DataSet can fetch multiple TableRows at a time

3.Provision of DataRelation Objects:
In DataSet, DataTable objects can be related to each other with DataRelation objects.

4.Enforcing Data Integrity:
In DataSet, data integrity is enforced by using the UniqueConstraint and ForeignKeyConstraint objects.

5.DataSource can be Serialized or Not:
DataSet is serialized DataSource .That is why web services can always returns DataSet as the result but not the DataTables.
Difference between DataReader,DataTable,Dataset?

1. Its an connection oriented, whenever you want fetch the data from database that you need the connection. after fetch the data connection is diconnected.
2. Its an Read only format, you cann’t update records.

1. Its connectionless. whenever you want fetch data from database. its connects indirectly to the database and create a virtual database in local system. then disconnected from database.
2. Its easily read and write data from virtual database.

A DataTable object represents a single table in the database. It has a name rows and columns.
There is not much difference between dataset and datatable, dataset is just the collection of datatables.

DataReader is a forward-only iterate over a set of results. it,s connection oriented and only loads one record at a time.
A dataset is an in-memory representation of a database-like structure. It can have one or more datatables and define relations between them, key or any fields etc.
A datatable is an in-memory representation of a single db table. You can think of it as having columns and rows in the same way.


Provides a means of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
The SqlDataReader can only retrieve one row at a time from the data source and in order for it to get the next record,
it has to maintain its connection to the data source. A DataReader is a stream of data that is returned from a database query. When the query is executed, the first row is returned to the DataReader via the stream.
The stream then remains connected to the database, poised to retrieve the next record.


The DataTable is a central object in the ADO.NET library. Other objects that use the DataTable include the DataSet and the DataView.
The DataTable also contains a collection of Constraint objects that can be used to ensure the integrity of the data.


The DataSet, which is an in-memory cache of data retrieved from a data source, is a major component of the ADO.NET architecture. The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects.
You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.

Difference between Dataset, datatable and dataview?

A dataset is an in-memory representation of a database-like structure. It can have one or more datatables and define relations between them, key field etc.
A datatable is an in-memory representation of a single database table. You can think of it as having columns and rows in the same way.
A dataview is a view on a datatable, a bit like a sql view. It allows you to filter and sort the rows – often for binding to a windows form control.

a DataReader is a forward-only iterator over a set of results. It’s usually the most efficient way to deal with records when you don’t need random access (in other words you can’t go backwards). It is “scalable” to any number of records, at least in terms of memory pressure, since it only loads one record at a time. One typical way to get a DataReader is by using the ExecuteReader method of a DbCommand.

a DataSet represents a set of DataTable objects. More often than not, it will just contain one table, but if you do a query with multiple SELECT statements, the DataSet will contain a table for each. Because this is an in-memory representation, you have to be careful about how much data you pull into a DataSet. You can “Fill” a DataSet using the Fill method of a DataAdapter.

a DataAdapter is a kind of “pipe” that funnels data from a DB engine into a DataSet. That’s why you’ll have one DataAdapter implementation for each DB provider type. One DataSet, many providers.

a DataView is like a virtual subset of a DataTable.

Dataset is a disjointed (an instance of the actual data from a datasource like SQL Server or Access, by having a dataset you don’t need to waste repeated calls back to the original source over the web.

A dataview. Every dataset can have multiple views, just like views with datatables. Dataviews are subsets of a dataset. A dataview could show the same information or less information than the dataset. Every dataset has a dataview and by default if you do not specify, it is dataview(0). When people say they are binding the dataset, they are actually binding dataset.dataview(0).

Datesets and dataviews are like thoughts in your head. People can mess with your head, but not actually see your thoughts. Getting the thoughts into some physical display for people to view, like writing thoughts on a piece of paper, is the datagrid, which usually outputs like a spreadsheet. The term binding the dataset to the datagrid can be thought of as binding your thoughts thru your hand via a pen to a piece of paper. Start thinking Gridview(.Net2) instead of old datagrid.

DataReader – The datareader is a forward-only, readonly stream of data from the database. This makes the datareader a very efficient means for retrieving data, as only one record is brought into memory at a time. The disadvantage: A connection object can only contain one datareader at a time, so we must explicitly close the datareader when we are done with it. This will free the connection for other uses. The data adapter objects will manage opening and closing a connection for the
command to execute

DataAdapter – Represents a set of SQL commands and a database connection that are used to fill the DataSet and update the data source. It serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. By using it, DataAdapter also automatically opens and closes the connection as and when required.

DataSet – The DataSet is the centerpiece of a disconnected, data-driven application; it is an in-memory representation of a complete set of data, including tables, relationships, and constraints. The DataSet does not maintain a connection to a data source, enabling true disconnected data management. The data in a DataSet can be accessed, manipulated, updated, or deleted, and then reconciled with the original data source. Since the DataSet is disconnected from the data source, there is less contention for valuable resources, such as database connections, and less record locking.

DataView – A major function of the DataView is to allow for data binding on both Windows Forms and Web Forms. Usually, a DataView data component is added to the project to display a sub-set of the records in a DataSet or DataTable. It also acts as filtered and sorted view of data to the DataTable.

DataTable – Represents one table of in-memory data. A DataTable stores data in a similar form to a database table: data is stored in a set of fields (columns) and records (rows). The DataTable class is a central class in the ADO.NET architecture; it can be used independently, and in DataSet objects. A DataTable consists of a Columns collection, a Rows collection, and a Constraints collection. The Columns collection combined with the Constraints collection defines the DataTable schema, while the Rows collection contains the data.
Difference between Hashtable and Dictionary?

When we want a collection data structure to hold data as key/value pairs, we have two obvious choices.

1. Dictionary

2. Hashtable

So basically what is the difference between both this and when to use which. Lets check it out. Point by Point.

1) Generics

Dictionary is a generic type, Hashtable is not. Now what that means. This is the most important aspect one should consider when taking decision. Dictionary is a generic type means

– You get type safety with Dictionary, because you can’t insert any random object into it, and you don’t have to cast the values you take out.

– And also generic collections are a lot faster as there’s no boxing/unboxing

– Hashtable uses Object to hold things internally (Only non-generic way to do it). So you have to take care of type safety and cast it to appropriate data type when you take it out, but it also means that you can add keys and values of any type ( It is good or bad, well it depends 🙂 )

– Again Hashtable also have to box/unbox, which may have memory consumption as well as performance penalties.

2) Thread Safety :

In .Net Hashtable is thread safe for use by multiple reader threads and a single writing thread, while in Dictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.

One more thing that can make difference is, we can not use dictionary (generics) with web services. The reason is no web service standard supports generics standard.

1. Hashtable is threadsafe and while Dictionary is not.
2. Dictionary is types means that the values need not to boxing while Hashtable
values need to be boxed or unboxed because it stored the values and keys as
3. When you try to get the value of key which does not exists in the collection, the
dictionary throws an exception of ‘KeyNotFoundException’ while hashtable returns
null value.
4. When using large collection of key value pairs hashtable would be considered more
efficient than dictionary.
5. When we retrieve the record in collection the hashtable does not maintain the order
of entries while dictionary maintains the order of entries by which entries were added.
6. Dictionary relies on chaining whereas Hashtable relies on rehashing.

HashTable stored data in form of DictionaryEntry class which holds key and value in form of object so if you are storing key and value as value types there will be boxing and unboxing issue and if there are some wrong values entered you wont get error at compile time but exception at runtime.

Dictionary holds data as KeyValuePair<T,T> and thus is strongly types which gives you compile time type checking as well as performance improvement while working with value types compared to hashtable since you dont need to unbox and box

Dictionaty is always faster compare to ArrayList since it maintains indexes and also secure since data is encrypted..
Difference between List, HashTable and Dictionary?

According to http://msdn.microsoft.com/en-us/library/ms379571(v=vs.80).aspx, a Hash table is the fastest data structure in C# when you know the number of records you are going to store because of the collision resulution method.

The better performance of a Hshtable over a Dictionary is doubtful however, due to boxing/unboxing which occurs when using a HashTable (http://msdn.microsoft.com/en-us/library/4yh14awz(v=vs.80).aspx).

Some sources say that HastTable is simply used for backward compability, and the new programs should always use a Dictionary.

My approach will be to use a Dictionary when I have to search for records and a List when I simply add new records or process records one by one. I will be curious to test the performance of a HastTable over a Dictionary though for a fixed-size array.
what is main difference between hashtable and arraylist?

Following are the main differences
Array List
1.Array List is a List
2.In this we can only add items to the list
3.Here we Can Add any datatype value,Every item in
arraylist is treated as object

Hash Table
1.Hash Table is a map
2.Here we can add data with the key
3.Retrieving by key in Hashtable is faster than retrieving in

In terms of performance, ArrayList / Hashtables are same, as both are derived from Array.

I would rather prefer List<T> / Dictionary<key,value> rather than them. Generics are Type safe and works faster than normal Arrays.

Also if you are looking for real performance u would better be using LinkedList<T>. It works faster for large array of data. I have seen somebody have made a good research to these. I cant find it now, but I will let u know when I find that.

So ranking :
1. LinkedList (For Large List)
2. List<T>, Dictionary<T>
3. Array, ArrayList, HashTable

Array List..
1.Array List is a List
2.In this we can only add items to the list
3.Here we Can Add any datatype value,Every item in
arraylist is treated as object

Hash Table..
1.Hash Table is a map
2.Here we can add data with the key
3.Retrieving by key in Hashtable is faster than retrieving in
ArrayList and Hashtable Contain two parameter first is Key and other is Value but ArrayList Key must be numeric and in case of Hash Table key may be numeric or Alpha.

Secondly Arraylist is slower as compare to Hashtable..

hashtable is basically use for maintaining huge data but arraylist dont have

One another related to this topic is StringDictionary this too much faster than these Arraylist and Hashtable using System.collection.


What are the differences between Hashtable, Dictionary and KeyValuePair?

Hashtable is an untyped associative container that uses DictionaryEntry class to return results of enumeration through its key-value pairs.

Dictionary<K,T> is a generic replacement of Hashtable that was introduced in C# 2.0. It uses KeyValuePair<K,T> generic objects to represent its key-value pairs.

The only place where you should see Hashtable these days is legacy code that must run on .NET 1.1, before generics have been introduced. It’s been kept around for compatibility reasons, but you should prefer Dictionary<K,T> whenever you can.

One major difference is that Hashtable is thread-safe, while Dictionary is not.

Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. To support multiple writers all operations on the Hashtable must be done through the wrapper returned by the Synchronized method, provided that there are no threads reading the Hashtable object.

A Dictionary(Of TKey, TValue) can support multiple readers concurrently, as long as the collection is not modified.

KeyValuePair is the unit of data stored in a Hashtable (or Dictionary). They are not equivalent to each other.

A key value pair contains a single key and a single value. A dictionary or hashtable contains a mapping of many keys to their associated values.

KeyValuePair is useful when you want to store two related pieces of information as a single unit, especially when one is related to the other in an identifying way (for instance 1234 => “David Smith”). They are also what you get back when you iterate a dictionary. In .NET 4.0, these are really only meant for use internally in a Dictionary- the Tuple class has been introduced for general purpose use.

The difference between Hashtable and Dictionary is that Hashtable is not a generic class- both it’s keys and values are of type Object. Dictionary is generic, and should generally be used in favor of Hashtable in any new development.

Difference between KeyValuePair VS DictionaryEntry?
KeyValuePair<TKey,TValue> is used in place of DictionaryEntry because it is generified. The advantage of using a KeyValuePair<TKey,TValue> is that we can give the compiler more information about what is in our dictionary. To expand on Chris’ example (in which we have two dictionaries containing <string, int> pairs).

Dictionary<string, int> myDictionary = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in myDictionary) {
int i = item.Value;

Hashtable myHashtable = new Hashtable();
foreach (DictionaryEntry item in myHashtable) {
// Cast required because compiler doesn’t know it’s a <string, int> pair.
int i = (int) item.Value;

What is the difference between LINQ and ADO.net?

Linq is a language feature (Language INtegrated Query) that allows for querying of objects. It is often conflated with Linq to Sql, which is a series of extension methods and other code that allows querying of a Sql Server database using Linq statements.

You can write a Linq provider to query any kind of datasource, for example, there is a Linq to Amazon provider that allows you to retrieve results from Amazon’s public API.
Why KeyValuePair is used instead of DictionaryEntry in generic Dictionary class?

KeyValuePair is a generic type, really KeyValuePair<TKey, TValue>, so it makes sense with the generic Dictionary<TKey, TValue> collection.

It reduces the need for casts (thus improving Intellisense and making your code less prone to runtime errors), as the following examples illustrate.

Dictionary<string, int> genericDict = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> kv in genericDict)
string s = kv.Key;
int i = kv.Value;

Hashtable nonGeneric = new Hashtable();
foreach (DictionaryEntry ent in nonGeneric)
string s = (string)ent.Key;
int i = (int)ent.Value;
If you are using KeyValuePair then the typecasting of object is not required as Opposed to DictionaryEntry in HashTable.
Iteration won’t require a typecasting.

But if you accessing the object you taken as part of iteration in that case if its diectoryentry you need a typecast.


Difference between LINQ to SQL and ADO.NET?


1)Used for data handling with SQL Server databases only.

2)Uses the extension methods of System.Linq.Queryable class.

3)Introduced in .net Framework 3.0

4)DataContext is used for Database connectivity.

5)Syntax and coding is somewhat complex.

6)Uses Entity classes.


1)Used for data handling with any database: SQL Server/Access/Oracle/Excel etc.

2)Does not use the extension methods of System.Linq.Queryable class.

3)There since the .net Framework 1.0

4)SqlConnection/OleDbConnection are used for database connectivity

5)Easier syntax and coding.
Note: Both LINQ TO SQL and ADO.NET have connexted/disconnected modes of data

What is the difference between ADO.NET Entity Framework and LINQ?

Entity Framework advantages over LINQ to SQL:

Enables you to build a conceptual model of the database rather than purely working with a 1:1 domain model of the database as objects (such as having one object mapped to multiple database tables, inheritance support, and defining complex properties).

Able to generate a database from your entity model. Support for databases other than just SQL Server. Support for many-to-many relationships.

Lazy loading and eager loading support.

Synchronization to get database updates will not lose your customizations to your model. Will continue to evolve, whereas LINQ to SQL development will from now on be minimal.

LINQ to SQL and the Entity Framework have a lot in common, but each have features targeting different scenarios in the Orcas timeframe.

LINQ to SQL has features targeting “Rapid Development” against a Microsoft SQL Server database. Think of LINQ to SQL as allowing you to have a strongly-typed view of your existing database schema. LINQ to SQL supports a direct, 1:1 mapping of your existing database schema to classes; a single table can be mapped to a single inheritance hierarchy (i.e. , a table can contain persons, customers, and employees) and foreign keys can be exposed as strongly-typed relationships. You can build LINQ queries over tables/views/table valued functions and return results as strongly typed objects, and call stored procedures that return strongly typed results through strongly typed methods.

A key design principle of LINQ to SQL is that it “just work” for the common cases; so, for example, if you access a collection of orders through the Orders property of a customer, and that customer’s orders have not previously been retrieved, LINQ to SQL will automatically get them for you.

LINQ to SQL relies on convention, for example default insert, update, and delete logic through generated DML can be overwritten by exposing appropriately named methods (for example, “InsertCustomer“, “UpdateCustomer“, “DeleteCustomer“). These methods may invoke stored procedures or perform other logic in order to process changes.

The Entity Framework has features targeting “Enterprise Scenarios“. In an enterprise, the database is typically controlled by a DBA, the schema is generally optimized for storage considerations (performance, consistency, partitioning) rather than exposing a good application model, and may change over time as usage data and usage patterns evolve. With this in mind, the Entity Framework is designed around exposing an application-oriented data model that is loosely coupled, and may differ significantly, from your existing database schema. For example, you can map a single class (or “entity”) to multiple tables/views, or map multiple classes to the same table/view. You can map an inheritance hierarchy to a single table/view (as
in LINQ to SQL) or to multiple tables/views (for example, persons, customers, and employees could each be separate tables, where customers and employees contain only the additional columns not present in persons, or repeat the columns from the persons table). You can group properties into complex (or “composite”) types (for example, a Customer type may have an “Address” property that is an Address type with Street, City, Region, Country and Postal code properties).

The Entity Framework lets you optionally represent many:many relationships directly, without representing the join table as an entity in your data model, and has a new feature called “Defining Query” that lets you expose any native query against the store as a “table” that can be mapped just as any other table (except that updates must be performed through stored procedures). This flexible mapping, including the option to use stored procedures to process changes, is specified declaratively in order to account for the schema of the database evolving over time without having to recompile the application.

The Entity Framework includes LINQ to Entities which exposes many of the same features as LINQ to SQL over your conceptual application data model; you can build queries in LINQ (or in “Entity SQL”, a canonical version of SQL extended to support concepts like strong typing, polymorphism, relationship navigation and complex types), return results as strongly typed CLR objects, execute stored procedures or table valued functions through strongly-typed methods, and process changes by calling a single save method.

However, the Entity Framework is more than LINQ to Entities; it includes a “Storage Layer” that lets you use the same conceptual application model through low-level ADO.NET Data Provider interfaces using Entity SQL, and efficiently stream results as possibly hierarchical/polymorphic DataReaders, saving the overhead of materializing objects for read-only scenarios where there is no additional business logic.

The Entity Framework works with Microsoft SQL Server and 3rd party databases through extended ADO.NET Data Providers, providing a common query language against different relational databases through either LINQ to Entities or Entity SQL.

So while there is a lot of overlap, LINQ to SQL is targeted more toward rapidly developing applications against your existing Microsoft SQL Server schema, while the Entity Framework provides object- and storage-layer access to Microsoft SQL Server and 3rd party databases through a loosely coupled, flexible mapping to existing relational schema.

I know this is a confusing area, and we’re trying to figure out how best to describe these differences to help customers make the appropriate choices. Please let me know if this helps, or if there are still areas of confusion…

Difference between Linq to SQL and the ADO.NET Entity Data Model?

LINQ to SQL supports rapid development of applications that query Microsoft SQL Server databases using objects that map directly to SQL Server schemas. LINQ to Entities supports more flexible mapping of objects to Microsoft SQL Server and other relational databases through extended ADO.NET Data Providers.

If you are writing an application that requires any of the following features, you should use the ADO.NET Entity Framework:

· The ability to define more flexible mapping to existing relational schema, for example:
o Mapping a single class to multiple tables
o Mapping to different types of inheritance
o Directly Modeling Many to Many relationships
o Mapping to an arbitrary query against the store
· The ability to query relational stores other than the Microsoft SQL Server family of products.
· The ability to share a model across Replication, Reporting Services, BI, Integration Services, etc.
· A full textual query language
· The ability to query a conceptual model without materializing results as objects

If you do not require any of these features, LINQ to SQL may provide a simpler solution for rapid development. LINQ to SQL is targeted at rapid-development scenarios against Microsoft SQL Server and provides a simpler approach and richer design experience in the Orcas timeframe for applications with data classes that map directly to the schema of your Microsoft SQL Server database.

Microsoft is defining a migration plan for customers that start with LINQ to SQL and require additional functionality, such as richer mapping capabilities or access to other stores, to migrate to the ADO.NET Entity Framework.


Advantages & Disadvantages of LINQ?

Quick turn around for development
Queries can be dynamically
Tables are automatically created into class
Columns are automatically created into properties
Relationship are automatically appeaded to classes
Lambda expressions are awesome
Data is easy to setup and use


No clear outline for Tiers
No good way of view permissions
Small data sets will take longer to build the query than execute
There is an overhead for creating queries
When queries are moved from sql to application side, joins are very slow
DBML concurrency issues
Hard to understand advance queries using Expressions
I found that programmers used to Sql will have a hard time figuring out the tricks with LINQ. But programmers with Sql knowledge, but haven’t done a ton of work with it, will pick up linq quicker.

I was writing linq before I took a Sql class in college, linq was alot simplier. Same with an current intern. The experienced programmers need to learn a new syntax, that used to be standard.
down vote
Advantages L2S offers:

No magic strings, like you have in SQL queries
Compile check when database changes
Faster development
Unit of work pattern (context)
Auto-generated domain objects that are usable small projects
Lazy loading.
Learning to write linq queries/lambdas is a must learn for .NET developers.
Regarding performance:

Most likely the performance is not going to be a problem in most solutions. To pre-optimize is an anti-pattern. If you later see that some areas of the application are to slow, you can analyze these parts, and in some cases even swap some linq queries with stored procedures or ADO.NET.
In many cases the lazy loading feature can speed up performance, or at least simplify the code a lot.
Regarding debuging:

In my opinion debuging Linq2Sql is much easier than both stored procedures and ADO.NET. I recommend that you take a look at Linq2Sql Debug Visualizer, which enables you to see the query, and even trigger an execute to see the result when debugging.
You can also configure the context to write all sql queries to the console window, more information here
Regarding another layer:

Linq2Sql can be seen as another layer, but it is a purely data access layer. Stored procedures is also another layer of code, and I have seen many cases where part of the business logic has been implemented into stored procedures. This is much worse in my opinion because you are then splitting the business layer into two places, and it will be harder for developers to get a clear view of the business domain.

LINQ in general

Query in-memory collections and out-of-process data stores with the same syntax and operators
A declarative style works very well for queries – it’s easier to both read and write in very many cases
Neat language integration allows new providers (both in and out of process) to be written and take advantage of the same query expression syntax
LINQ to SQL (or other database LINQ)

Writing queries where you need them rather than as stored procs makes development a lot faster: there are far fewer steps involved just to get the data you want
Far fewer strings (stored procs, parameter names or just plain SQL) involved where typos can be irritating; the other side of this coin is that you get Intellisense for your query
Unless you’re going to work with the “raw” data from ADO.NET, you’re going to have an object model somewhere anyway. Why not let LINQ to SQL handle it for you? I rather like being able to just do a query and get back the objects, ready to use.
I’d expect the performance to be fine – and where it isn’t, you can tune it yourself or fall back to straight SQL. Using an ORM certainly doesn’t remove the need for creating the right indexes etc, and you should usually check the SQL being generated for non-trivial queries.
It’s not a panacea by any means, but I vastly prefer it to either making SQL queries directly or using stored procs.

LINQ to SQL versus ADO.NET?


ADO.NET is our contemporary data access component and now we have written many applications. Now there has been a lot of talk on LINQ to SQL. So we are little skeptical about this component and trying to find some relation between existing ADO.NET technology.
Purpose of this post is to give some quick brief on some major differences between ADO.Net and LINQ to SQL. I have not used 100% code as this is just to give an idea. The database I have used here is Northwind (SQL Server 2000 Sample database).

Some comparison,
Scenario 1


Establishing connection between database and application,

using(SqlConnection conn = new SqlConnection(“Connection String”))





You create a .dbml file and give a name (assume “NW.dml”). Then there will be a DataContext class created. So you need to initialize the instance of an object.

NWDataContext db = new NWDataContext(“Connection String”);

You do not need to call any Open() method. Datacontext handles well the open and close method.

Scenario 2


Getting data from database,


using(SqlConnection conn = new SqlConnection(“Connection String”))


using (SqlCommand comm = new SqlCommand(“Select * from Customers”))



SqlDataReader reader = comm.ExecuteReader();

DataTable dt = new DataTable(“New Table”);





using (NorthwindDataContext db = new NorthwindDataContext())


//You can also use “var” at “IEnumerable<Customer>”

IEnumerable<Customer> custs = from c in db.Customers

select c;

foreach (Customer c in custs)





WOW!!! I have received comment from our Senior Program Manager Dinesh Kulkarni from LINQ to SQL team when I requested him to visit my blog. He mentioned,

DataTable provides you a cache that can be re-enumerated without DB roundtrip while LINQ to SQL results need to be explicitly cached with something like a ToList()/ToArray(). Identity caching in DataContext aside, the L2S code is closer to enumerating a DataReader. Although DataReader does not allow you to re-enumerate and requires another ExecuteReader, the impact of reenumerating L2S query is the same – another roundtrip to DB.

Scenario 3


Inserting into the database,


using(SqlConnection conn = new SqlConnection())



SqlCommand comm = new SqlCommand(“INSERT INTO…”, conn);




using (NorthwindDataContext db = new NorthwindDataContext())


//Create a new object

Customer c = new Customer();

c.CustomerID = “ABCDE”;

//…. add all the properties you need to add while inserting

//Add it to the collection


//Save the changes to the database



Scenario 4


Updating database,


Same as Scenario 3


using (NorthwindDataContext db = new NorthwindDataContext())


//Get the object from database

Customer cust = (from c in db.Customers where c.CustomerID == “ALFKI” select c).First();

//Update the exsisting value

cust.CompanyName = “I do not know?”;

//Save the changes to the database



Scenario 5


Deleting records from the database,


Same as Scenario 3


using (NorthwindDataContext db = new NorthwindDataContext())


//Get the object from database

Customer cust = (from c in db.Customers where c.CustomerID == “ALFKI” select c).First();

//Remove it from collection


//Save the changes to the database



Scenario 5


Executing stored proc which returns record(s),


using(SqlConnection conn = new SqlConnection())



using (SqlCommand comm = new SqlCommand(“SalesByCategory”, conn))


comm.CommandType = CommandType.StoredProcedure;

comm.Parameters.AddWithValue(“@param1”, “value1”);

comm.Parameters.AddWithValue(“@param2”, “value2”);

SqlDataReader reader = comm.ExecuteReader();




In LINQ to SQL it becomes metod as you drag and drop it to .dbml file,

using (NorthwindDataContext db = new NorthwindDataContext())


var outPut = db.SalesByCategory(“SeaFood”, “1998”);


LINQ to SQL vs ADO.NET Entity Framework?

LINQ to SQL and ADO.NET Entity Framework are extensions of ADO.NET and are introduced to avoid difficulties involved in writing programs using object oriented programming languages to access data residing in RDBMS. Both have provided mechanisms to de-couple pure business logic and underlying data access logic (which is provided within the framework) with the help of LINQ (Language-Integrated Query) and thus allowing to query data using programming language’s own syntax. Thus both allow representing data in the relational database as business objects and also represent relations within the objects (including inheritance).

While speaking about similarities or differences, we understand that ADO.NET Entity Framework’s LINQ to Entities can be considered as superset of LINQ to SQL and that, ADO.NET Entity Framework is much more than LINQ to Entities.

LINQ to SQL can be used for rapid application development while ADO.NET Entity Framework can be used for enterprise application development.

LINQ to SQL can only support MS SQL Server database (also its compact version) however, external vendors are developing data providers for MySQL, Oracle, Postgres, etc. ADO.NET Entity Framework is built on top of ADO.NET data provider model and thus supports all existing ADO.NET data providers.

LINQ to SQL allows developers to generate .NET classes that directly map respective database tables or views. This leads to 1:1 mapping between class and table. This means that it looses the flexibility of an object representing a part of table or one object representing data from multiple tables. On the other hand, ADO.NET Entity Framework allows developers to generate .NET classes that map to conceptual data model. This leads to m:n mapping between classes and tables and thus has the flexibility of an object representing a part of table or one object representing data from multiple tables. Due to this flexibility, DBA can make changes to the database for improving performance, partitioning, etc. without affecting business logic.

Thus LINQ to SQL is targeted for developing rapid applications which can support MS SQL database and have simple mapping of business objects to relational data while ADO.NET Entity Framework is targeted for developing Enterprise applications which can support MS SQL databases as well as other databases through extended ADO.NET data provider and also have complex mapping of business objects to the persistent data.


1 – L2SQL is essentially obsolete

2 – L2SQL does not support POCO mapping, EF does.

3 – EF has more flexibility (code first, model first, database first). L2SQL has only 1.

4 – EF has support for SPROC -> POCO mapping

5 – EF has Entity-SQL, allowing you to go back to classic ADO.NET when required

6 – EF supports inheritance (TPT, TPH)

7 – EF goes hand-in-hand with Repository pattern, and deferred execution via IQueryable

8 – EF components (ObjectSet, ObjectContext) are easily mockable and allow for DI


Difference between Generics and Collections with example?

Non-Generic collections – These are the collections that can hold elements of different data types. It holds all elements as object type.
So it includes overhead of type conversions.

– Generic collections – These are the collections that can hold data of same type and we can decide what type of data that collections can hold.

Some advantages of generic collections – Type Safe, Secure, reduced overhead of type conversions.

Collections can hold different data type. Here all the elements are objects.


In generics, we can specify which datatype we want to store.
Use the following links for examples

Non-Generic collection which collection can hold the different type of data.
Generic collection which collection can hold the same type of data.
and the deference between collections and generics are:
Collections are enumerable data structures that can be assessed using indexes or keys.Using generic collection classes provides increased type-safety and in some cases can provide better performance, especially when storing value types.

With help of Generics you can avoid boxing and unboxing problems.
Generics involves type-safety.
For more details, you can read this Generics

Collection Classes have the following properties:
– Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace.
– Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator and their generic equivalents.

But for you to note, in NET exists terms of Generic collection.
Generic collection provide increased type-safety and in some cases can provide better performance, especially when they store value types.

The System.Collections namespace should be used.

Collections examples: ArrayList , IEnumerator, Hashtable , SortedList.

Generic Collections Examples List<T> and Dictionary<TKey, TValue>

Non-Generic collections – These are the collections that can hold elements of different data types. It holds all elements as object type.
So it includes overhead of type conversions.

Generic collections – These are the collections that can hold data of same type and we can decide what type of data that collections can hold.

Some advantages of generic collections – Type Safe, Secure, reduced overhead of type conversions.
Non – Generic collection class – which collection can hold the different type of data.

Generic collection class – which collection can hold the same type of data.

Collections are enumerable data structures that can be assessed using indexes or keys.Using generic collection classes provides increased type-safety and in some cases can provide better performance, especially when storing value types

Difference between a cookie session and Session state mode?


When ever the new Session is created ASP.NET will generate an In-memory cookie to store the


In case if the cookies are disabled in browser then the Sessionid will be appended in the URL.

Session has an attribute in web.config file which state that either you want session to be cookieless or not.

By default, the ASP.NET session object uses a client-side cookie to store an identifier. This identifier is used to locate the session across server round trips. However, it also supports a cookieless session mode that initially redirects the client to a new URL containing the session ID, and then automatically parses the session ID out of the URL.
Session in ASP.net is used to store data, it stores almosty all .net serializable data (in “InProc” mode). As session is stores on the server side & it’s never transmitted to client it called to be very secure. Client & server communicate with each other on the basis a unique session ID for that clients and stored in Session State Provider.

Session can be maintained in two ways. cookies and cookieless.

By default your sessionid is stored on client machine inside a cookie. whenever you make a request this cookie is sent to server.

But sometimes cookies are disabled on client machine. In such cases sessions are maintained in “cookieless” manner. This is nothing but encoded sessionid in url. So each time you make a request to server, your sessionid is encoded and that packet is attached in your querystring. By this your application’s session is maintained irrespective to cookies enabled or disabled.

Difference between Session vs Cache?

The key difference is session is per user, while cache will be for application scoped items.

Another difference is:
Items put into a session will stay there, until the session ends.
Items in the cache can expire (will be removed from cache) after a specified amount of time. And also there is no guaranty that objects will not be removed before their expiration times as ASP.NET remove items from cache when the amount of available memory gets small. This process is called as Scavenging.

Another difference is:
The session state can be kept external (state server, SQL server) and shared between several instances of your web app (for load balancing).
This is not the case with the cache.

Session: Session is used to store data,It is user specific. It can be accessible through out the site. Session has 4 modes:

In Proc ( Data is stored in memory )
State Service ( Data is stored in a service, the benefit is if your application restarts session still exits )
Sql Server ( same benefit as state server has )
In Proc ( without cookies ) a session_id is attached to URL. THis is used when user has disabled cookies.

Session[“key”] = “value”; // You can store any object data type.
Cache: There are two types of cache in asp.net.

Page Output Caching: You can cache the whole page by specifying the PageOutput direcitve at the top of the page.It store’s the rendered page in the Cache. It is used when your page is accessed by thousands of users, so to increase the response time, we cache that page.
Application Caching: It allows to store any object in memory and automatically removed the object based on some limitations e.g time or some other dependencies . Example:

Cache[“key”] = “value”; // it also supports any object data type.

Remember Cache and Session are different things.

A Session is available for a user till the application is alive and the session is not abandoned.

Well a cache can be made available for the enitre application level or user level

One major difference between both is that you items in cache can expire after given time to cahce well as items in session will stay till session expires.

Caching is storing data in memory for quick access. Typically information that is costly to obtain (in terms of performance) is stored in the cache. One of the more common items stored in a cache in a Web application environment is commonly displayed database values; by caching such information, rather than relying on repeated database calls, the demand on the Web server and database server’s system resources are decreased and the Web application’s scalability increased.

Session variables can also be used to cache information in classic ASP, although, as with the cookie approach each session variable is specific to a particular user, and to tie a session variable to a particular user the user’s browser must accept cookies. The advantages of using session variable’s over cookies is that you can store objects, such as an array, or Dictionary object. Since session variables are stored on the Web server’s memory, storing large objects in a user’s session on a site with many simultaneous users can lead to reduced memory on the Web server.

Difference between Session and Cookies
1. The main difference between cookies and sessions is that cookies are stored in the user’s browser, and sessions are not.
2. But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.
3. The Key difference would be cookies are stored in your hard disk whereas sessions aren’t stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
4. A session as is a server-side object which stores State. A cookie is a small piece of information a browser sends to a server with every request.
5. Session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browse
6. Session and cookies differ in type and amount of information they are capable of storing.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s