Dotnet difference questions and answers compiled- 1(updated-2)


Published on

This provides huge collection (165+) of DOTNET Technology FAQs which are of "Difference Between" type. For further updates, please visit my blog @

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Dotnet difference questions and answers compiled- 1(updated-2)

  1. 1. 1) What are the differences between DataReader and DataAdapter? S.No DataReader DataAdapter 1 Works in Connected Mode Works in Disconnected Mode 2 Can have only one record at a time Can have more than 1 records 3 Is ForwardOnly and Readonly Can navigate front and back and editable 4 Faster Slower2) What are the differences between DataSet and DataReader? S.No DataSet DataReader 1 Works in Disconnected Mode Works in Connected Mode 2 Can navigate back and forth Can navigate forward only 3 Data is editable Data is Readonly 4 Can contain more than one table Can contain only one row at a time and relationships 5 Slower as having more overhead Faster when compared with DataSet3) What is the difference between DataSet.Copy() and DataSet.Clone()? S.No DataSet.Copy() DataSet.Clone() 1 DataSet.Copy() copies both the DataSet.Clone() copies the structure of structure and data the DataSet, including all DataTable schemas, relations, and constraints and it does not copy any data4) What are the differences between RecordSet and DataSet? S.No RecordSet DataSet 1 RecordSet provides data of one row DataSet is a data structure which at an instant represents the complete table data at the same time 2 RecordSet always needs an Open DataSet needs connection only for connection to read the data from retrieving the data. After retrieve the data sources data connection is not necessary 3 RecordSet is able to load the DataSet has the capability to store the structure and data of only one table structure and data of multiple tables at a at a time time 4 RecordSet does not support DataSet enforces data integrity by using constraints of Databases Constraints5) What are the differences between ADO and ADO.Net? S.No ADO ADO.Net
  2. 2. 1 It supports connected model It supports disconnected model2 It uses record set It uses data set3 XML support is less XML support is more
  3. 3. 1.Difference between Typed DataSet and Untyped DataSet S.No Typed DataSet Untyped DataSet 1 It provides additional methods, It is not as easy to use as strongly properties and events and thus it typed dataset. makes it easier to use. 2 They have .xsd file (Xml Schema They do not do error checking at the definition) file associated with design time as they are filled at run them and do error checking time when the code executes. regarding their schema at design time using the .xsd definitions. 3 We will get advantage of We cannot get an advantage of intelliSense in VS. NET. intelliSense. 4 Performance is slower in case of Performance is faster in case of strongly typed dataset. Untyped dataset. 5 In complex environment, strongly Untyped datasets are easy to typed datasets are difficult to administer. administer. 6 Typed DataSets use explicit UnTyped DataSets use table and names and DataTypes for their column collections for their members members. ex: ex: ds.Tables["emp"].Columns["eno"].Rea northwindDataSet.Products.Produ dOnly=true; ctNameColumn.Caption = "pnames";2.Difference between DataView and DataTable S.No DataView DataTable 1 Read-only i.e., DataView can be Read/Write i.e., Datatable can be used used to select the data. to edit or select or delete or insert a data. 2 Is a reference to an existing Can be created empty and then DataTable. Cannot be populated populated from scratch; must be instantiated with a reference to an existing DataTable. 3 Data is a reference to an existing Data takes storage space. DataTable, and does not consume space.
  4. 4. 4 Can sort or filter rows without Can add/edit/delete rows, columns, modifying the underlying data. and data, and all changes are Rows and columns can be hidden persistent. and revealed repeatedly. 5 Can return a DataTable version Can be cloned of the view 6 A live reference to a Is source data; does not contain DataTable; any changes in the references DataTable data is immediately reflected in the view. 7 Supports calculated columns, Does not support calculated columns which are columns with a value calculated on the fly by combining or manipulating other columns. 8 Can hide or show selected No row or column hiding columns3.Difference between Connected and Disconnected Environment S.No Connected Environment Disconnected Environment 1 Connected Environment needs a Disconnected Environment does not constantly connection of user to need any connection. data source while performing any operation. 2 Only one operation can be Multiple operations can be performed. performed at a time in connection Environment. 3 DataReader is used in Connection DataSet is used in it. Environment. 4 It is slower in speed. Disconnected Environment has a good speed. 5 We get updated data in it. There is a problem of dirty read.Please visit my blog @
  5. 5. 1) What are the differences between Inline code and Code Behind Code? S.No Inline code Code Behind Code 1 Its within .aspx file Its in a external class file 2 Dynamically compiled Compiled prior to deployment and linked with .aspx file2) What are the differences between Global.asax and Web.Config? S.No global.asax web.config 1 It is a class file It is an XML file 2 There can be only one for an There can be many if under different application sub-folders 3 Can have Application and Session Cannot have Application and Session events events 4 Need to be recompiled when No need to compile when changes are changes are made made3) What are the Differences between Server.Transfer and Response.Redirect? S.No Server.Transfer Response.Redirect 1 The navigation happens on the The navigation happens on the client- server-side ,so client history is side ,so client history is updated not updated 2 Data can be persist across the Context.Items loses the persistence pages using Context.Item collection 3 No Round-trips Makes a Round-trip 4 Has Good encapsulation No4) What is the difference between a custom control and a user control? S.No User Control Custom Control 1 Is a file with the .ascx extension Is a file with the .dll extension 2 Can be only used with the Can be used in any number of application applications 3 Language dependent They are language independent, a control created in c# can be used in 4 Cannot be added to Visual studio Can be added to Visual studio Toolbox Toolbox 5 Inherits from Server controls and We have to develop from scratch , easy to create so comparatively difficult 6 Generally used for static content Used when dynamic content is required5) What is the difference between Caching and Application? S.No Caching Application 1 Cache have expire policy Application does not have expire policy 2 Cache does not require explicit Application require explicit locking locking 3 Cache has the Property of timeout, Application variables exist as long as
  6. 6. which allows us to control the the application is alive duration of the Objects so cached 4 Output can be cached in 4 ways, Application does not have options as  Page Output Caching like Cache object  Page Partial Caching  DataSource Caching  Data Caching 5 It is accessible to page level to all It is accessible to both page level and the users application level to all the users6) What is the difference between web farm and web garden? S.No Web farm Web garden 1 A web application running on A web application running on a single multiple servers is called a web server that has multiple CPUs is farm called a web garden7) What is the difference between Application and Session Events? S.No Application Event Session Event 1 Application events are used to Session events are used to initialize initialize objects and data that we data that we want to keep throughout do want to make available to all individual sessions, but that we do not the current sessions of our web want to share between sessions application8) What is the difference between Session Cookies and Persistent Cookies? S.No Session Cookies Persistent Cookies 1 Session Cookies do not have Persistent Cookies have an expiration expiration date date. The expiration date indicates to the browser that it should write the cookie to the client’s hard drive9) What are the differences between Server Controls and HTML Controls? S.No Server Controls HTML Controls 1 Server Controls can trigger HTML Controls can trigger only control-specific events on the page-level events on server (postback) server 2 Data entered in a server control is Data is not maintained in an HTML maintained across requests. Server control. Data must be saved and controls retain state restored using page-level scripts 3 The Microsoft .NET Framework HTML controls have HTML attributes provides a set of properties for only each server control. Properties allows us to change the server control’s appearance and behavior within server-side code 4 Server controls automatically We must detect browser in code or detect browser and adapt display write for least common denominator as appropriate10) What are the differences between ViewState and Hidden fields? S.No ViewState Hidden fields 1 This is used for pages that will This is used for pages that will postback to itself postback to itself or to another page
  7. 7. 2 This is built in structure for This is not an inbuilt structure maintaining state of a page 3 Security is more as data is hashed, Security is less when compared to compressed and encoded ViewState11) What is the difference between SQL Cache Notification and SQL Cache Invalidation? S.No SQL Cache Notification SQL Cache Invalidation 1 Using SQL Cache Notification, Using SQL Cache Invalidation, we we can generate notifications can make a cached item invalid that when the data of a database on depends on the data stored in a SQL which a cached item depends server database, when the data in the changes SQL server database is changed12) What is the difference between absolute time expiration and sliding time expiration? S.No Absolute time expiration Sliding time expiration 1 In absolute time expiration, a In sliding time expiration, the time for cached item expires after the which the item is cached is each time expiration time specifies for it, incremented by its expiration time if it irrespective of how often it is is accessed before completion of its accessed expiration time13) What is the difference between adding items into cache through Add() method and Insert() method? S.No Cache.Add() Cache.Insert() 1 Cache.Add() method also returns Cache.Insert() method adds only the an object representing the item we item in the cache have added in the cache ,besides adding the item in the cache 2 It is not possible to replace an We can replace an existing item in the existing item in the cache using cache using the Cache.Insert() method the Cache.Add() method14) What is the difference between page-level caching and fragment caching? S.No Page-level caching Fragment caching 1 In Page-level caching, we cache In Fragment caching, we cache parts a whole page of the web page such as a user control added to the web page15) What is the difference between Label control and Literal control? S.No Label control Literal control 1 Final HTML code of a Label Final HTML code of a Literal control control has an HTML tag contains only text, which is not surrounded by any HTML tag16) What is the difference between HyperLink control and LinkButton control? S.No HyperLink control LinkButton control 1 A HyperLink control do not have A LinkButton control have Click and Click and Command events Command events, which can be handled in the code behind file of the web page
  8. 8. 17) What is the difference between an HtmlInputCheckBox control and an HtmlInputRadioButton control? S.No HtmlInputCheckBox control HtmlInputRadioButton control 1 We can select more than one We can select only a single HtmlInputCheckBox control from HtmlInputRadioButton control from a a group of HtmlInputCheckBox group of HtmlInputRadioButton controls controls18) How a content page differs from a master page? S.No Content page Master page 1 A content page does not have A master page has complete HTML complete HTML source code source code inside its source file19) How will you differentiate a submaster page from a top-level master page? S.No Submaster page Top-level master page 1 Like a content page, a submaster Top-level master page has complete page also does not have complete HTML source code inside its source HTML source code file20) What is the difference between a page theme control and a global theme? S.No Page theme Global theme 1 A page theme is stored inside a A global theme is stored inside the subfolder of the App_Themes Themes folder on a web server folder of a web application 2 It can be applied to individual web It can be applied to all the web sites pages of the web application on the web server21) What is the difference between a default skin and a named skin? S.No Default skin Named skin 1 A default skin does not have a A named skin has a SkinId attribute SkinId attribute 2 It is automatically applied to all It is applied to a control explicitly by the controls of the same type setting the SkinId property of the present on a web page control from the Properties window22) Differentiate Globalization and Localization S.No Globalization Localization 1 Globalization is the process of Localization is the process of identifying the specific portion of configuring a web application to be a web application that needs to be supported for a specific language or different for different languages locale and isolating that portion from the core of the web application23) What are the differences between web.config and machine.config? S.No web.config machine.config 1 This is automatically created This is automatically installed when when we create an ASP.Net web we install Visual Studio. Net application project 2 This is also called application This is also called machine level level configuration file configuration file
  9. 9. 3 We can have more than one Only one machine.config file exists web.config file on a server4 This file inherits setting from the This file is at the highest level in the machine.config configuration hierarchy
  10. 10. Difference between Web site and Web application S.No Web site Web application 1 Can mix vb and c# page in single We cant include c# and vb page in single website. web application. 2 Can not establish dependencies. We can set up dependencies between multiple projects. 3 Edit individual files after Can not edit individual files after deployment. deployment without recompiling. 4 Right choice when one developer Right choice for enterprise environments will responsible for creating and where multiple developers work unitedly for managing entire website. creating,testing and deployment. i.e.,In web site development, i.e.,In Web application, different different decoupling is not possible. groups work on various components independently like one group work on domain layer, other work on UI layer. 5 Web site is easier to create than Web Web application is more difficult to create application than a Web siteDifference between Local storage and cookies S.No Local storage Cookies 1 Good to store large amount of data, Good for small amount of data, up to 4KB up to 4MB 2 Easy to work with the JavaScript Difficult to work with JavaScript 3 Local storage data is not sent to the All data is transferred to and from server, so server on every request (HTTP bandwidth is consumed on every request header) as it is purely at the client side 4 No way to specify the time out Can specify timeout period so that cookies period as the Cookies have data are removed from browserDifference between Session and Cache S.No Session Cache 1 Ssession retains state per user Cache is used for retaining state for application scoped items. 2 Items put into a session will stay Items in the cache can expire (will be there, until the session ends 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. 3 The session state can be kept external This is not the case with the cache. (state server, SQL server) and shared between several instances of our web app (for load balancing).
  11. 11. Difference between Datalist and Repeater S.No Datalist Repeater 1 Datalist supports multiple columns Repeater doesnt support multiple columns displaying and using repeat columns display,no repeat columns property property 2 Datalist supports styles for formating Repeater does not provide styles templates data[headerstyle,...] 3 Datalist rendering output[html Repeater performanace is better than Datalist content]will be slow compare with repeater.Summary:If the requirement can achieve using repeater and datalist,choose repeater for better performance
  12. 12. 1.Difference between ASP.NET and PHP S.No ASP.NET PHP 1 Technology Availability: Technology Availability: ASP.NET was launched by PHP was launched by Rasmus Lerdorf Microsoft in the year 2002. in the year 1995. 2 Database: Database: ASP.Net uses MS-SQL for For point of database connectivity PHP connecting database but MS-SQL uses MySQL for the purpose of can not be availed free from database connectivitybecasue its Microsoft. highly flexiblilty nature. Another important fact is that it will incurextra expenditure because MySQL can be accessed for free. 3 Cost: Cost: We need to install Internet Linux can be used for running PHP Information Server (IIS)on a programs and Linux is free operating Windows server platformif you system. Therefore,the cost of want to run ASP.Net program. As developing a website in PHP language Windows server platform is not a is remarkably low free product,the cost of production is bounded to be increased. 4 Run Time : Run Time: It has been observed that ASP.Net Whereas inbuilt memory space is used code runs slower than PHP code. by PHP while running. This is becauseASP.Net utilizes server space while running 5 Coding Simplicity: Coding Simplicity: ASP.Net codes are somewhat PHP codes are very simple and a complicated and a web developer programmer does not haveto make a needs to work hard to get the hang diligent effort because it is of it comparatively easier than other types of programming languages. 6 Platform Connectivity Issue : Platform Connectivity Issue: ASP.NET codes are usually run on PHP has a unique advantagein this Windows platforms but if you issue. Its codes can be linked with install ASP-Apache inthe server different types of platforms such than it can run on Linux platform asWindows, Linux and UNIX. as well. 7 Cost of Tools : Cost of Tools :
  13. 13. There is no such free tools are PHP codes are available for free in available for ASP.Net. various forums and blogs as it is a open source software. Furthermore, some useful tools that can be used in PHP are also availablefor free 8 Language Support : Language Support : The syntax of ASP.Net is more or The codes that are used in PHP are less similar to that of Visual basic very much similar to that of C++ syntax and this is all but simple. language and its syntax resembles the syntax used in C and C++. Therefore, if you have a fair knowledge in C++ or C, you will not face any difficulty while coding PHP language. 9 Security : Security : ASP. Net is reputedfor creating Though PHP can offer enough sophisticated techniques to ensure measures for ensuring data security the safety of confidential data.This is the reason why government organizations opt for ASP.Net.2.Difference between ASP and ASP.NET S.No ASP ASP.NET 1 ASP is a request response model. ASP.NET is a programming model that is event driven. 2 ASP code is an interpreted ASP.NET is a compiled CLR code that language that is interpreted by the will be executed on the Server. script engine. 3 HTML and the coding logic are The code and design logic is separated mixed in ASP. in ASP.NET. 4 To develop and debug ASP ASP.NET application can be application, there are very limited developed and debugged using various tools. tools including the leading Visual Studio .NET tool. 5 ASP has limited support to Object ASP.NET is a complete Object Oriented Programming principles. Oriented Programming language. 6 Session management and ASP.NET extends complete support application state management is for session management and
  14. 14. very limited in ASP. application state management. 7 Error handling system is poor in ASP.NET offers complete error ASP. handling and exception handling services. 8 ASP does not offer any in-built In ASP.NET, data exchange is easily support for the XML. performed using XML support. 9 Data source support is not fully Data source support is fully distributed distributed in ASP. in ASP.NET.3.Difference between ASP.NET and VB.NET S.No ASP.NET VB.NET 1 ASP.NET is web technology that VB.NET is a language that is used in is used in building web writing programs that are utilizing the applications and websites. ASP.NET framework. 2 ASP.NET is a server side VB.NET is a .NET programming technology that is language language. VB.NET is used to create independent. Any .NET languages ASP.NET web applications or such as C#, VB.NET can be used windows applications using Visual to develop web applications Studio Windows Forms Designer or through ASP.NET. mobile applications or console applications or applications for variety of other purposes. 3 ASP.NET is included within VB.NET is not part of .NET the .NET framework. framework. For example, ASP.NET contains For example, VB.NET is the code that the text boxes and the controls is written on various events of text that can be dragged and dropped boxes and controls to make them into a web form. function as per the requirement. 4 ASP.NET contains server VB.NET does not include server controls. controls. 5 ASP.NET can support all .NET VB.NET can support only scripting languages. languages.
  15. 15. 4.Difference between Java and .NET S.No Java .NET 1 JAVA is developed by ‘Sun .NET is developed by ‘Microsoft’. Microsystem‘ 2 JAVA is a programming .NET is a framework that supports language many programming languages like C#,ASP,VB. 3 In JAVA, JVM(Java Virtual In .NET CLR(common language Machine) execute the code and Runtime) execute the code with two convert source code to byte code. phase compilation. 4 JAVA can run on any operating .NET can run only on windows/IIS. system 5 But in JAVA it depends upon the Although .NET support both explicit programmer to destroy the and implicit garbage garbage memory. collection,especially,in .NET the garbage collector destroy the garbage value in an efficient manner as compared to JAVA. 6 JDBC is used for database ADO .NET is use for database connection in JAVA connection in .NET. 7 For java many third party IDEs .net has a standard development IDE are available. i.e. Microsoft Visual Studio 8 But web application in java run on Both windows and web applications any operating system. can developed by .net but it will be more better to go for windows application with .NET . you can also go for web application with .NET but it will only hosted on windows server. 9 Exception Handling in Java is Exception Handling in .NET is harder than .NET simpler than JAVA. 10 JAVA uses bootclasspath for .NET uses GAC(Global Assembly completely trusted codes. Cache) and keep trusted assemblies. 11 Java is less secure than .NET JAVA and .NET both have similar while providing security security goals. But .NET is more secure because of its simple and clean designs. 12 Java JDBC which requires .Net due to disconnected data access multiple round trips to data base. through ADO.Net has high level of Hence, performance is lesser performance against Java JDBC than .NET
  16. 16. 13 Development is comparatively Due to Microsoft Visual Studio, slower. development is faster. 14 Java applications development Microsoft Visual Studio installation can be done on even less requires higher configuration system. configuration computer system. 15 Java can only communicate with .Net is the platform itself for a java programs multitude of languages. One can use C, C++ and VB to program upon .net. These programs interact with each other using common methods. these common methods are defined by .Net, and are used by the programs to communicate with each other without worry about that language the program was written in. the machine running the program/s will need the .Net platform to be installed.Please visit my blog @
  17. 17. 1.Difference between HTTP and HTTPS S.No HTTP HTTPS 1 URL begins with “http://" in case URL begins with “https://” in case of of HTTP HTTPS. 2 HTTP is unsecured HTTPS is secured. 3 HTTP uses port 80 for HTTPS uses port 443 for communication communication. 4 HTTP operates at Application HTTPS operates at Transport Layer. Layer 5 No encryption is there in HTTP HTTPS uses encryption. 6 No certificates required in HTTP certificates required in HTTPS. 7 Most internet forums will HTTPS should be used in Banking probably fall into this category. Websites, Payment Gateway, Shopping Because these are open discussion Websites, Login Pages, Emails (Gmail forums, secured access is offers HTTPS by default in Chrome generally not required browser) and Corporate Sector Websites. For example: PayPal: Google AdSense: between GET and POST methods S.No GET POST 1 Post Mechanism: Post Mechanism: GET request is sent via URL. Post request is sent via HTTP request body or we can say internally. 2 Form Default Method: Form Default Method: GET request is the default We have to specify POST method method. within form tag like <Form method="POST"....... 3 Security: Security: Since GET request is sent via Since Post request encapsulated name URL, so that we can not use this pair values in HTTP request body, so method for sensitive data. that we can submit sensitive data through POST method.
  18. 18. 4 Length: Length: GET request has a limitation on POST request has no major limitation. its length. The good practice is never allow more than 255 characters. 5 Caching or Bookmarking: Caching or Bookmarking: GET request will be better for POST request is not better for caching caching and bookmarking. and bookmarking. 6 SEO: SEO: GET request is SEO friendly. POST request is not SEO friendly. 7 Data Type: Data Type: GET request always submits data POST request has no restriction. as TEXT. 8 Best Example: Best Example: SEARCH is the best example for LOGIN is the best example for POST GET request. request. 9 HTTP Request Message HTTP Request Message Format: Format: 1 POST /path/script.cgi HTTP/1.0 1 GET /path/file.html? 2 From: SearchText=Interview_Question 3 User-Agent: HTTPTool/1.0 HTTP/1.0 4 Content-Type: application/x-www- 2 From: form-urlencoded 3 User-Agent: HTTPTool/1.0 5 Content-Length: 8 4 [blank line here] 6 7 Code=132Some comments on the limit on QueryString / GET / URL parameters Length:1. 255 bytes length is fine, because some older browser may not support more than that.2. Opera supports ~4050 characters.3. IE 4.0+ supports exactly 2083 characters.4. Netscape 3 -> 4.78 support up to 8192 characters.5. There is no limit on the number of parameters on a URL, but only on the length.6. The number of characters will be significantly reduced if we have special characters like spacesthat need to be URLEncoded (e.g. converted to the %20).7. If we are closer to the length limit better use POST method instead of GET method.
  19. 19. 3.Difference between User Controls and Master Pages S.No User Controls Master Pages 1 Its extension is .ascx. Its extension is .Master. 2 Code file: .ascx.cs or .ascx.vb code file: .master.cs or .master.vb extension 3 A page can have more than one Only one master page can be assigned User Controls. to a web page 4 It does not contain It contains ContentPlaceHolder. Contentplaceholder and this makes it somewhat difficult in providing proper layout and alignment for large designs. 5 Suitable for small designs(Ex: More suitable for large designs(ex: logout button on every .aspx defining the complete layout of .aspx page.) page) 6 Register Tag is added when we MasterPageFile attribute is added in drag and drop a user control onto the Page directive of the .aspx page the .aspx page. when a Master Page is referenced in .aspx page. 7 Can be attached dynamically Can be referenced using Web.Config using LoadControl method.PreInit file also or dynamically by writing event is not mandatory in their code in PreInit event. case for dynamic attachment.4.Difference between Build and Rebuild S.No Build Rebuild 1 A build compiles only the files A rebuild rebuilds all projects and files and projects that have changed. in the solution irrelevant of whether they have changed or not. 2 Build does not updates the xml- Rebuild updates the xml- documentation files documentation filesNote: Sometimes,rebuild is necessary to make the build successful. Because, Rebuild cleansSolution to delete any intermediate and output files, leaving only the project and component files,from which new instances of the intermediate and output files can then be built.
  20. 20. 5.Difference between generic handler and http handler S.No Generic Handler Http Handler 1 Generic handler has a handler http handler is required to be which can be accessed by url with configured in web.config against .ashx extension extension in web.config.It does not have any extension 2 Typical example of generic For http handler, page handler which handler are creating thumbnails of serves .aspx extension request and give images response.Please visit my blog @
  21. 21. 1.Difference between ViewState and SessionState S.No ViewState SessionState 1 View state is maintained in page Session state is maintained in session level only. level. 2 View state of one page is not Session state value is available in all visible in another page.i.e., when pages within a user session.i.e., The user requests another page data will be no longer available if user previous page data will be no close the browser or session timeout longer available. occurs. 3 View state information stored in Session state information stored in client only. server. 4 View state persist the values of Session state persist the data of particular page in the client particular user in the server. This data (browser) when post back available till user close the browser or operation done. session time completes. 5 View state used to persist page- Session state used to persist the user- instance-specific data. specific data on the server side.2.Difference between ViewState and ControlState S.No ViewState ControlState 1 ViewState can be disabled Control State cannot be disabled. 2 ViewState is implemented by Control State works even when using EnableViewState property EnableViewState is off. of a control to true. To use Control State (for example in a custom control) we have to override OnInit method,call RegisterRequiresControlState method in OnInit method and then override the SaveControlState and LoadControlState methods. 3 ViewState is used to maintain Control State is used for small data page-level state for large data only. eg: maintain clicked page number in a GridView even when EnableViewState is off
  22. 22. 3.Difference between SessionState and Cookies S.No SessionState Cookies 1 Session can store any type of data Cookies can store only "string" because the value is of datatype of datatype "object" 2 These are stored at Server side They are stored at Client side 3 Session are secured because it is Cookie is non-secure since stored in stored in binary format/encrypted text format at client side form and it gets decrypted at server 4 Session is independent for every Cookies may or may not be individual client i.e individual for every for every client client 5 There is no limitation on size or Due to cookies network traffic will number of sessions to be used in increase.Size of cookie is limited to 40 an application and number of cookies to be used is restricted to 20. 6 For all conditions/situations we Only in few situations we can use can use sessions cookies because of no security 7 We cannot disable the We can disable cookies sessions.Sessions can be used without cookies also(by disabling cookies) 8 The disadvantage of session is Since the value is string there is no that it is a burden/overhead on security server 9 Sessions are called as Non- We have persistent and non-persistent Persistent cookies because its life cookies time can be set manuallyPlease visit my blog @
  23. 23. 1.Difference between DataGrid and GridView S.No DataGrid GridView 1 Sorting: In DataGrid code Sorting: In case of GridView no requires to handle the additional code required. SortCommand event and rebind grid required. 2 Paging: In DataGrid requires Paging: In case of GridView no code to handle the additional code required. It also PageIndexChanged event and supports customized appearance. rebind grid required. 3 Data binding: Like GridView Data binding: GridView can bind DataGrid cannot bind with new with new datasource control datasource control in ASP.NET 2.0. 4 Updating data: DataGrid Updating data: GridView requires requires extensive code to update little code. Code like exceptions operation on data handling for database part. 5 Events: In DataGrid less events Events: GridView supports events supported as compared to fired before and after database updates. GridView.2.Difference between ListView and GridView S.No ListView GridView 1 Data Grouping: In-built support Data Grouping: To provide this for this functionality is provided. functionality, we need to write custom code. 2 Provide Flexible Layout: In-built Provide Flexible Layout: To provide support for this functionality is this functionality, we need to write provided. custom code 3 Insert: In-built support for this Insert: To provide this functionality, functionality is provided. we need to write custom code
  24. 24. 3.Difference between DataList and GridView S.No DataList GridView 1 Paging: To provide this Paging: In-built support for this functionality, we need to write functionality is provided. custom code. 2 Provide Flexible Layout: In-built Provide Flexible Layout: To provide support for this functionality is this functionality, we need to write provided. custom code 3 Update,Delete: To provide this Update,Delete: In-built support for functionality, we need to write this functionality is provided. custom code 4 Data Grouping: In-built support Data Grouping: To provide this for this functionality is provided. functionality, we need to write custom code. 5 Sorting:To provide this Sorting:In-built support for this functionality, we need to write functionality is provided. custom code.4.Difference between Repeater and ListView S.No Repeater ListView 1 Paging: To provide this Paging: In-built support for this functionality, we need to write functionality is provided. custom code. 2 Data Grouping: To provide this Data Grouping: In-built support for functionality, we need to write this functionality is provided. custom code. 3 Insert: To provide this Insert: In-built support for this functionality, we need to write functionality is provided. custom code 4 Update,Delete: To provide this Update,Delete: In-built support for functionality, we need to write this functionality is provided. custom code 5 Sorting:To provide this Sorting:In-built support for this functionality, we need to write functionality is provided. custom code.
  25. 25. 5.Difference between Repeater and DataList S.No Repeater DataList 1 Repeater is template driven DataList is rendered as Table. 2 Repeater cannot automatically DataList can automatically generates generates columns from the data columns from the data source source 3 Row selection is not supported by Row selection is supported by DataList Repeater 4 Editing of contents is not Editing of contents is supported by supported by Repeater DataList 5 Arranging data items horizontally We can arrange data items horizontally or verticlaly is not supported by or verticlaly in DataList RepeaterPlease visit my blog @
  26. 26. New features of ASP.Net 2.0, ASP.Net 3.0 and ASP.Net 3.5- AComparative ChartSNo ASP.Net 2.0 ASP.Net 3.0 ASP.Net 3.51 a) Generics a) Windows a) Linq for SQL, XML, Dataset, b) Anonymous Communication Object methods Foundation (WCF), b) Addin system c) Partial class formerly called c) p2p base class d) Nullable type Indigo; a service- d) Active directory e) The new API gives oriented messaging e) ASP.NET Ajax a fine grain control system which allows f) Anonymous types with on the behavior of programs to static type inference the runtime with interoperate locally g) Paging support for regards to or remotely similar to ADO.NET multithreading, web services. h) ADO.NET synchronization memory b) Windows API to synchronize local allocation, Presentation caches and server side assembly loading Foundation (WPF), datastores. and more formerly called i) Asynchronous network I/O f) Full 64-bit support Avalon; a new user API for both the x64 interface subsystem j) Support for HTTP and the IA64 and API based on pipelining and syndication hardware XML and vector feeds. platforms graphics, which uses k) New System.CodeDom g) New 3D computer namespace. personalization graphics hardware features for and Direct3D ASP.NET, such as technologies. support for c) Windows Workflow themes, skins and Foundation (WF) webparts. allows for building of h) .NET Micro task automation and Framework integrated transactions using workflows. d) Windows CardSpace, formerly called InfoCard; a software component which securely stores a persons digital identities and
  27. 27. provides a unifiedinterface forchoosing the identityfor a particulartransaction, such aslogging in to awebsite
  28. 28. 1.Difference between C# 3.5 and C# 4.0 S.No C# 3.5 C# 4.0 1 C# 3.5 does not support dynamic C# 4.0 supports dynamic programming programming. through dynamic objects. 2 The dynamic keyword is not In C# 4.0, dynamic keyword is recognized in C# 3.5. associated with objects to represent them as dynamic objects. 3 Dynamic variables cannot be C# 4.0 allows creation of dynamic created in C# 3.5. variables. 4 In C# 3.5, method parameters In C# 4.0, the method parameters can cannot be specified with default be specified with default values using values. C# 3.5 does not support optional parameters. optional parameters. 5 In C# 3.5, method parameters C# 4.0 provides named parameters to have to be specified in the same represent the values of method order as in method declaration in parameters without following the order the method call. C# 3.5 does not of declaration. provide named parameters. 6 In C# 3.5, usage of ref keyword is In C# 4.0, usage of ref keyword is mandatory while executing optional while executing methods methods which are supplied by which are supplied by the COM the COM interfaces. interfaces. 7 The COM object’s indexed The COM object’s indexed properties properties are not recognized in are recognized in C# 4.0. C# 3.5. 8 Co-variance and contra-variance C# 4.0 enhances Generics by are not supported in Generics of introducing co-variance and contra- C# 3.5. variance.2.Difference between C# and VB.NET S.No C# VB.NET 1 In C#, variables are declared using In VB.NET, the variables are declared declarators. using keywords such as private, protected, friend, public, static, shared and Dim. 2 In C#, an object can only be In VB.NET, an object can be created created using new. using new and CreateObject(). 3 In C#, void is specified as the In VB.NET, Sub is used in method return type when a method does declaration to indicate that the method
  29. 29. not return a value. does not return any value.4 In C#, no keyword is required to In VB.NET, Overloads keyword is indicate an overloaded method. used to indicate an overloaded method.5 The current object is referred The current object is referred as me in using this pointer in C#. VB.NET.6 Non virtual call cannot be made in To make a non-virtual call to the C#. current object’s virtual method, MyClass is used in VB.NET.7 Compound data type is declared Compound data type is declared in in C# using class, struct and VB.NET using Structure. interface.8 In C#, constructors are used to In VB.NET, Sub New() is used to initialize an object. initialize the newly created object.9 Object cleanup can be explicitly Object cleanup can be done by using done by destructor in C#. Finalize method in VB.NET.10 In C#, an object is subject to In VB.NET, an object cannot be asynchronous modification using modified in an asynchronous way. volatile keyword.11 In C#, all the variables have to be In VB.NET, variables can be forced for declared before being used. explicit declaration using Option Explicit.12 In C#, default property is defined In VB.NET, default property is defined by using indexers. using Default.13 In C#, base class can be referred In VB.NET, base class can be referred using the keyword ‘base’. using the keyword ‘MyBase’.14 Abstract class of C# can only be MustInherit keyword of VB.NET is inherited and not instantiated. used to denote that a class can only be inherited and not instantiated.15 Sealed keyword of C# is used to NotInheritable keyword of VB.NET denote that a class cannot be denotes that the class cannot involve in inherited. inheritance.16 Division can be performed in C# Division can be performed in VB.NET using / operator. using operator.17 Remainder of division can be Remainder of division can be retrieved retrieved using mod operator of using %. C#.18 C# does not have exponentiation In VB.NET, exponentiation can be operator. performed using ^ operator.
  30. 30. 19 C# has Bitwise operators namely Bitwise operators in VB.NET are And, &,| and ^. Or, Xor. 20 Object reference variables can be Object reference variables can be compared using == operator in compared using Is operator in C#. VB.NET. 21 The short ciruit operators in C# The short circuit operators in VB.NET are && (Boolean AND) and || are AndAlso (Boolean AND) and (Boolean OR). OrElse (Boolean OR).3.Difference between C# and C++ S.No C# C++ 1 C# is a high level language that is C++ is a low level and indeed platform component oriented. neutral programming language. 2 When compiled, C# code is When compiled, C++ code is converted into Intermediate converted into assembly language language code. This intermediate code. language code is converted into executable code through the process called Just-In-Time compilation. 3 In C#, memory management is In C++, the memory that is allocated in automatically handled by garbage the heap dynamically has to be collector. explicitly deleted. 4 In C# Switch Statement, the test In C++ Switch Statement, the test variable can be a string. variable cannot be a string. 5 In C# switch statement, when In C++ switch statement, when break break statement is not given, the statement is not given, the fall through fall through will not happen to the will happen to the next case statement next case statement if the current even if the current case statement has case statement has any code. any code. 6 In addition to for, while and C++ does not contain for each do..while, C# has another flow statement. control statement called for each. 7 C# struts can contain only value C++ struts behave like classes except types. The struts is sealed and it that the default access is public instead cannot have a default no-argument of private. constructor. 8 In C#, delegates, events and In C++, only variables, constructors, properties can also be specified as functions, operator overloads and class members. destructors can be class members.
  31. 31. Delegates, events and properties cannot be specified as class members. 9 In C#, the end of the class In C++, the end of the class definition definition has a closing brace has a closing brace followed by a alone. semicolon. 10 The access modifiers in C# are The access modifiers in C++ are public, private, protected, internal public, private, protected. C++ does and protected internal. not have internal and protected internal access modifiers. 11 C# has finally block in exception C++ does not have finally block in handling mechanism. The code exception handling mechanism. statements in the finally block will be executed once irrespective of exception occurrence. 12 The exception in C# can only The exception in C++ can throw any throw a class that is derived from class. the System.Exception class. 13 C# does not have the concept of C++ has the concept of function function pointers. C# has a similar pointers. concept called Delegates.Please visit my blog @
  32. 32. 1. Difference between Factory Pattern and Abstract Factory Pattern S.No Factory Pattern Abstract Factory Pattern 1 Create object through inheritance Create object through composition 2 Produce only one product Produce families of products 3 Implements code in the abstract creator Concrete factories implements factory that make use of the concrete type that method to create product sub class produces2.Difference between Abstract Factory Pattern And Builder Pattern S.No Builder Pattern Abstract Factory Pattern 1 In Builder Pattern, there will be one Abstract Factory Pattern will return the Director class which will instruct Builder instance directly. class to build the different parts/properties of our object and finally retrieve the object. 2 It will have reference to the created It does not keep the track of its created object. object.3.Difference between Builder Pattern And Composite Pattern S.No Builder Pattern Composite Pattern 1 It is used to create group of objects of It creates Parent - Child relations between predefined types. our objects.4.Difference between MVC and MVP S.No MVP MVC 1 MVP is a bit more complex to MVC is easier to implement than MVP. implement than MVC .Also, it has additional layer for view interfaces. 2 The request is always received by the The request is received by the controller View and delegated to the presenter which in turn gets the required data and which in turn gets the data does the loads up the appropriate view processing 3 The presentation and view logic an be The controller logic can be unit tested. unit tested as the view is loosely Note: We can unit test view if we are using coupled. Razor view engine. ASPX viewengine are not that easily unit testable 4 MVP is best suitable for Windows MVC is best suitable for Web Programming. Programming as the flow naturally tend towards this pattern.
  33. 33. 5.Difference between Proxy Pattern and Observer Pattern S.No Proxy Pattern Observer Pattern 1 The Proxy Pattern is used for wrapping a The Observer Pattern is used by a publisher kind of special object with 1 or more object to notify subscriber objects with other objects. information. 2 Either because we dont always have the The publisher object does not know the wrapped object or because it needs to be subscribing objects - except that the managed in a certain way that can be conform to a certain subscriber interface. simplified via the proxy object(s). This is This is a very flexible pattern for kind of a way to exchange the API of an distributing events, since those that wants to existing class with a proxy class. We are listen on certain object has the power to do not just talking events here, but whatever so without changing the code of the kind of functionality to define via the publishing object. proxy object instead of the real object.6. Difference between Singleton Pattern and a static class S.No Singleton Pattern static class 1 Singleton pattern maintains single We cannot create instance for static class. instance. 2 A singleton can extend classes and A static class cannot . implement interfaces. Note: It can extend classes, but it does not inherit their instance members. 3 A singleton can be initialized lazily or A static class is generally initialized when it asynchronously. is first loaded, leading to potential class loader issues. 4 Singletons can be handled static class cannot be handled polymorphically without forcing their polymorphically. users to assume that there is only one instance. 5 Singleton Class can have value when Static are always just shared and have no Class object instantiated between server instance but multiple references. and client, such a way if three client want to have a shared data between them Singleton can be used.Thats why singleton class can be used for state mangement in stateless scenarios like shopping cart scenario. 6 We can pass singleton object as We cannot pass parameter in static class parameter 7 Singleton provides flexibility and also Static classes once defined could not provides sort of a mechanism to control accomodate any future design changes as by object creation based on various design static classes are rigid and cannot be requirements. They can be extended as extended. well if need arises. In other words we are not always tied to a particular implementation. With Singleton we
  34. 34. have the flexibility to make changes as when situation demands.7.Difference between Strategy and Inversion of Control (IOC) S.No Strategy Pattern Inversion of Control (IOC) Pattern 1 The strategy pattern is useful when we Inversion of Control/Dependency Injection want classes to depend on the interface (IoC/DI) comes into play when we want the rather than the implementation.And we concrete strategy implementation injected can easily swap out behavior depending into a class. For example, we could use the on which concrete implementation we DI Framework Ninject and configure it so provide. that it will know which concrete strategy implementation to inject into a class in specific scenarios. Note: Strategy is just one of the ways that IOC is implemented8.DIfference between IDictionary and Dictionary S.No IDictionary Dictionary 1 IDictionary is just a contract, abstraction Dictionary is concrete implementation. 2 It is recommended for example to expect Argument or Property is not required for as argument an IDictionary rather than Dictionary. concrete Dictionary, or to expose property of IDictionary rather than Dictionary, because this promotes loose coupling. Than we are able to change underlying objects in the future without affecting those who use your object.9.Difference between Factory Pattern and Dependency Injection S.No Factory Pattern Dependency Injection(DI) 1 Factory is used to create objects DI is used to move the responsibility of creating an object outside the main code. 2 Some of the well known framework available for DI are 1. Unity Application Block (Microsoft) 2. Ninject 3. StructureMap 4. Castle Windsor 5. Munq/Funq 6. Autofac
  35. 35. 10.Difference between String.Clone() and String.Copy() method S.No String.Clone() String.Copy() 1 Returns a reference to this instance of Creates a new instance of String with the String. same value as a specified String. i.e., it gives pointer value(ie Current i.e., it creates an instance in Heap Memory memory Reference) and gives pointer value(ie New Memory Reference)11.Difference between Strategy Pattern and Factory Pattern S.No Strategy Pattern Factory Pattern 1 Strategys sole intent to is to provide a Factorys sole purpose is to create objects . mechanism to select different algorithm. 2 We cannot use "strategy" to create We can use "factory" to create objects of objects of "factory". "strategy".12.Difference between Proxy and Adaptor S.No Proxy Pattern Adaptor Pattern 1 Proxy on the other hand represents a Adapter is used to adapt to incompatible standin object for the real object. This is interfaces. Its more directed from the client required when the real object is complex (those who consume the object) perspective. to create, is not available, or for A client expects an interface to be of authentication purpose. For e.g. web particular type and adapter plays a role in service proxy, proxy authentication filling that gap. server etc. Its more from making it easier for the client Proxy can be categorized into to adapt to other third party libraries within there own by adapting to it. Virtual Proxy Remote Proxy Protection Proxy13.Difference between Decorator and Visitor S.No Decorator Pattern Visitor Pattern 1 Decorator may have just a single object Visitor has a tree of objects to be worked to customize. upon. 2 Decorator does not require a traverser Visitor requires a traverser for successful for successful implementation. implementation. 3 Decorator pattern is a structural pattern Visitor pattern is Behavioral pattern that that help us to add new function to an seperate the data structure from the object in the run time , note that in the operation (functionality ) that work on it , run time not design time . this mean we can add different operation on the same data structure
  36. 36. Difference between ASP.Net 2.0 and ASP.Net 3.5SN Feature ASP.Net 2.0 ASP.Net 3.5o1 New ASP.Net 2.0 includes the ASP.Net 3.5 includes the Features following as new features, following as new features, a) Master Pages a) ListView Control b) Profiles b) DataPager Control c) GridView Control c) Nested Master Pages d) LinqDataSource Control2 Multi- ASP.Net 2.0 does not ASP.Net 3.5 supports multi- targeting support Multi-Targeting targeting. It means that we environment. choose from a drop-down list whether to have Visual Studio 2008 build applications against the ASP.NET 2.0, 3.0, or 3.5 frameworks.3 AJAX There is no in-built support In ASP.Net 3.5, AJAX is Support for AJAX in ASP.Net 2.0. integrated into the .NET Instead, it has to be Framework, thereby making the downloaded and installed. process of building intuitive cool user interfaces easier.4 Siverlight It does not support It supports Siverlight. Support Siverlight.5 Javascript It does not provide It provides Javascript debugging. Debugging Javascript debugging.6 LINQ It does not support LINQ. It Supports Language Integrated Support Query (LINQ).
  37. 37. 1) What is the difference between CCW and RCW? S.No CCW RCW 1 COM to .NET communication .NET to COM Communication happens happens through COM Callable through Runtime Callable Wrapper Wrapper2) What are the differences between Dll and Exe? S.No Dll Exe 1 Objects of Dlls can be created Objects of Exe cannot be created 2 Dll is In-Process Exe is Out-Process 3 It cannot be started as a standalone It can be started as a standalone3) What are the differences between Managed Code and Unmanaged Code? S.No Managed Code Unmanaged Code 1 It is executed under CLR It is not executed under CLR 2 It compiles to intermediate language It compiles directly to machine code 3 It provides services like security, It does not provide security, exception exception handling, garbage handling, garbage collection etc collection etc 4 It can access both managed and It can access only unmanaged code unmanaged code
  38. 38. 1.Difference between Finalize() and Dispose() methods in .NET S.No Finalize() Dispose() 1 Finalize() belongs to the Object Dispose() belongs to the IDisposable class. interface 2 It is automatically called by the We have to manually write the code to Garbage Collection mechanism implement it(User Code) when the object goes out of the ex: if we have emp class we have to scope(usually at the end of the inherit it from the IDisposable program) interface and write code. We may have to suppress the Finalize method using GC.SuppressFinalize() method. 3 It is slower method and not Faster method for instant disposal of suitable for instant disposing of the objects. the objects. Example: user interface Controls. Example: Forms, SqlConnection class have built in implementaion of Dispose method. class employee { //This is the destructor of emp class ~employee() { } //This destructor is implicitly compiled to the Finalize method. } 4 It is non-deterministic function It is deterministic function as i.e., it is uncertain when Garbage Dispose() method is explicitly called Collector will call Finalize() by the User Code. method to reclaim memory.2.Difference between Dispose and Destructor in .NET S.No Dispose Destructor 1 Unmanaged resources are It is used to release unused managed removed by dispose method and it resources and it is called automatically is called manually by the Garbage Collector 2 It is used to remove the unused It is used to de-allocate the allocated resources from the memory. memory by the constructor method
  39. 39. 3.Difference between Close() and Dispose() methods in .NET S.No Close() Dispose() 1 When a Close() method is Where as Dispose() method called,database connection will be permanently close and removes temporarily closed and can be connection object from memory and opened once again using Open() the resource no longer exists for any method. further processing. Note: However, calling Dispose does not remove the connection from the connection pool.Example:try{string constring = "Server=(local);Database=my; User Id=sa; Password=sa";SqlConnection sqlcon = new SqlConnection(constring); sqlcon.Open(); // here connection is open// some code here which will be execute}catch{ // code will be execute when error occurred in try block}finally{ sqlcon.Close(); // close the connectionsqlcon.Dispose(); // desroy the connection object}Note: Only call the Close method on a Stream or a database connection if the object will be reused.Otherwise, use the Dispose method.And, further updates on difference between questions and answers, please visit my blog @
  40. 40. Difference between hash table and arraylist S.No Arraylist Hash table 1 Array List is a List Hash Table is a map 2 Here, we can only add items to the list Here, we can add data with the key 3 Retrieving data using Arraylist is slower Retrieving by key in Hashtable is faster than than Hashtable because If we want to retrieving in Arraylist because If we want to find something in a arraylist we have to find something in a hashtable we dont have go through each value in arraylist. to go through each value in hashtable, instead search for key values and is faster.Difference between Hash Table and Arrays Hash Table Array Hash table stores data as name,value pair. Array stores only value To access value from hash table, we need to In array, to access value , we need to pass pass name. index number. We can store different type of data in hash In array ,we can store only similar table, say int,string etc. type of data.Difference between Dictionary and Hashtable Dictionary Hashtable Dictionary is a generic type Hashtable is not generic type. In Dictionary we need to specify the types of Hashtable is a collection of name/value pairs both the key and the corresponding value.The that are organised on the basis of hash code of value represents the actual object stored and the the key being specified. key represents a means to identify a particular object. In Dictionary public static members are type Hashtable is thread safe for use by multiple safe but any instance members are not type reader threads and a single writing thread. safe. We cannot use Dictionary with Web Services We can use Hashtable withWeb Services The reason is no web service standard supports generic standard. Dictionary is aster than Hashtable because It is slower than dictionary because to retrieve boxing is not required. a value we must cast it as its actual type, because it will be returned via object reference.
  41. 41. Difference between array and stack Array Stack An array can be multi-dimensional Stack is strictly one-dimensional An array allows direct access to any of its With a stack, only the top element is directly elements accessible; to access other elements of a stack, we must go through them in order, until we get to the one we wantDifference between Stack and Heap Stack Heap Memory will be allocated at the compile time. Memory will be allocated at the run time. Here the memory is allocated by the compiler. Here the memory is allocated by the user. Memory will be allocated only in sequential Memory will be allocated in sequential locations. locations and non- sequential locations. The memory will also be deleted by the The memory must be deleted explicitly by the compiler. user. There is lot of chance of memory wastage. There is no chance of memory wastage if the memory is handled perfectly.Difference between Array and ArrayList Array ArrayList They are fixed length. They are resizable and variable length They are compiled strong type collection. They are flexible and can accommodate any data types. Because arrays are of fixed size and strong In arraylist lots of boxing and unboxing are type collection performance is faster. done there for its performance is slower. Array is in the System namespace ArrayList is in the System.Collections namespace. Ex:Char[] vowel=new Char[]; Ex:ArrayList a_list=new ArrayList();
  42. 42. 1.Difference between for and foreach loop S.No For loop Foreach loop 1 In case of for the variable of the loop is In case of Foreach the variable of the loop always be int only. while be same as the type of values under the array. 2 The For loop executes the statement or The Foreach statement repeats a group of block of statements repeatedly until embedded statements for each element in an specified expression evaluates to false. array or an object collection. 3 There is need to specify the loop We do not need to specify the loop bounds bounds(Minimum, Maximum). minimum or maximum. 4 example: example: using sytem; using sytem; class class1 class class1 { { static void Main() static void Main() { { int j=0; int j=0; for(int i=0; i<=10;i++) int[] arr=new int[] { {0,3,5,2,55,34,643,42,23}; j=j+1; foreach(int i in arr) } { Console.ReadLine(); j=j+1; } } } Console.ReadLine(); } }2. Difference between Covariance and Contravariance S.No Covariance Contravariance 1 Converting from a broader type to a Converting from a more specific type to a specific type is called co-variance.If B broader type is called contra-variance. If B is is derived from A and B relates to A, derived from A and B relates to A, then we then we can assign A to B. Like A=B. can assign B to A. Like B= A. This is This is Covariance. Contravariance. 2 Co-variance is guaranteed to work Contra-variance on the other hand is not without any loss of information during guaranteed to work without loss of data. As conversion. So, most languages also such an explicit cast is required. provide facility for implicit conversion. e.g. Converting from cat or dog to animal is e.g. Assuming dog and cat inherits from called contra-variance, because not all animal, when you convert from animal features (properties/methods) of cat or dog is type to dog or cat, it is called co- present in animal. variance. 3 Example:
  43. 43. class Fruit { } class Mango : Fruit { } class Program { delegate T Func<out T>(); delegate void Action<in T>(T a); static void Main(string[] args) { // Covariance Func<Mango> mango = () => new Mango(); Func<Fruit> fruit = mango; // Contravariance Action<Fruit> fr = (frt) => { Console.WriteLine(frt); }; Action<Mango> man = fr; } }4 Note: 1. Co-variance and contra-variance is possible only with reference types; value types are invariant. 2. In .NET 4.0, the support for co-variance and contra-variance has been extended to generic types. No now we can apply co-variance and contra-variance to Lists etc. (e.g. IEnumerable etc.) that implement a common interface. This was not possible with .NET versions 3.5 and earlier.
  44. 44. 3.Difference between IList and IEnumerable S.No IList IEnumerable 1 IList is used to access an element in a IEnumerable is a forward only collection, it specific position/index in a list. can not move backward and between the items. 2 IList is useful when we want to Add or IEnumerable does not support add or remove remove items from the list. items from the list. 3 IList can find out the no of elements in Using IEnumerable we can find out the no of the collection without iterating the elements in the collection after iterating the collection. collection. 4 IList does not support filtering. IEnumerable supports filtering.4.Difference between IEnumerable and IQueryable S.No IEnumerable IQueryable 1 IEnumerable exists in IQueryable exists in System.Linq System.Collections Namespace. Namespace. 2 IEnumerable is best to query data from IQueryable is best to query data from out- in-memory collections like List, Array memory (like remote database, service) etc. collections. 3 While query data from database, While query data from database, IEnumerable execute select query on IEnumerable execute select query on server server side, load data in-memory on side with all filters. client side and then filter data. 4 IEnumerable is suitable for LINQ to IQueryable is suitable for LINQ to SQL Object and LINQ to XML queries. queries. 5 IEnumerable does not supports custom IQueryable supports custom query using query. CreateQuery and Execute methods. 6 IEnumerable does not support lazy IQueryable support lazy loading. Hence it is loading. Hence not suitable for paging suitable for paging like scenarios. like scenarios. 7 Extension methods supports by Extension methods supports by IEnumerable IEnumerable takes functional objects. takes expression objects means expression tree. 8 IEnumerable Example MyDataContext dc = new MyDataContext (); IEnumerable list = dc.loyees.Where(p => p.Name.StartsWith("S")); list = list.Take(10); Generated SQL statements of above query will be : SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0
  45. 45. Note: In this query "top 10" is missing since IEnumerable filters records on client side IQueryable Example MyDataContext dc = new MyDataContext (); IEnumerable list = dc.loyees.Where(p => p.Name.StartsWith("S")); list = list.Take(10); Generated SQL statements of above query will be : SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0 Note: In this query "top 10" is exist since IQueryable executes query in SQL server with all filters.5.Difference between IEnumerable and IEnumerator S.No IEnumerable IEnumerator 1 The IEnumerable interface is a generic IEnumerator provides two abstract methods interface that provides an abstraction and a property to pull a particular element in for looping over elements. a collection. And they are Reset(), In addition to providing foreach MoveNext() and Current The signature of support, it allows us to tap into the IEnumerator members is as follows: useful extension methods in the void Reset() : Sets the enumerator to its System.Linq namespace, opening up a initial position, which is before the first lot of advanced functionality element in the collection. The IEnumerable interface contains an bool MoveNext() : Advances the enumerator abstract member function called to the next element of the collection. GetEnumerator() and return an interface object Current : Gets the current element in IEnumerator on any success call. the collection 2 IEnumerable does not remember the IEnumerator does remember the cursor state cursor state i.e currently row which is iterating through 3 IEnumerable is useful when we have IEnumerator is useful when we have to pass only iterate the value the iterator as parameter and has to remember the value