All Differences in Dot Net

Embed Size (px)

Citation preview

  • 8/8/2019 All Differences in Dot Net

    1/34

    Difference between Interface and Abstract Class

    Interfaces vs. Abstract Classes

    Feature Interface Abstract class

    Multipleinheritance

    A class may implement severalinterfaces.

    A class may extend only oneabstract class.

    Defaultimplementation

    An interface cannot provide anycode at all, much less defaultcode.

    An abstract class can providecomplete code, default code, and/or

    just stubs that have to beoverridden.

    Constants

    Static final constants only, canuse them without qualification inclasses that implement theinterface. On the other paw,these unqualified names pollutethe namespace. You can usethem and it is not obvious wherethey are coming from since thequalification is optional.

    Both instance and static constantsare possible. Both static and

    instance intialiser code are alsopossible to compute the constants.

    Third partyconvenience

    An interface implementationmay be added to any existingthird party class.

    A third party class must be rewrittento extend only from the abstractclass.

    Is-a vs -able orcan-do

    Interfaces are often used todescribe the peripheral abilitiesof a class, not its central identity,

    e.g. an Automobile class mightimplement the Recyclableinterface, which could apply tomany otherwise totally unrelatedobjects.

    An abstract class defines the coreidentity of its descendants. If youdefined a Dog abstract class then

    Damamation descendants are Dogs,they are not merely dogable.Implemented interfaces enumeratethe general things a class can do,not the things a class is.

    Plug-in You can write a newreplacement module for aninterface that contains not onestick of code in common with theexisting implementations. Whenyou implement the interface, you

    start from scratch without anydefault implementation. Youhave to obtain your tools fromother classes; nothing comeswith the interface other than afew constants. This gives youfreedom to implement a radicallydifferent internal design.

    You must use the abstract class as-is for the code base, with all itsattendant baggage, good or bad.The abstract class author hasimposed structure on you.Depending on the cleverness of the

    author of the abstract class, thismay be good or bad. Another issuethat's important is what I call"heterogeneous vs. homogeneous."If implementors/subclasses arehomogeneous, tend towards anabstract base class. If they areheterogeneous, use an interface.

    http://dng-oops.blogspot.com/2007/05/difference-between-interface-and.htmlhttp://dng-oops.blogspot.com/2007/05/difference-between-interface-and.html
  • 8/8/2019 All Differences in Dot Net

    2/34

    (Now all I have to do is come upwith a good definition ofhetero/homogeneous in thiscontext.) If the various objects areall of-a-kind, and share a common

    state and behavior, then tendtowards a common base class. If allthey share is a set of methodsignatures, then tend towards aninterface.

    Homogeneity

    If all the variousimplementations share is themethod signatures, then aninterface works best.

    If the various implementations areall of a kind and share a commonstatus and behavior, usually anabstract class works best.

    Maintenance

    If your client code talks only interms of an interface, you caneasily change the concreteimplementation behind it, usinga factory method.

    Just like an interface, if your clientcode talks only in terms of anabstract class, you can easilychange the concrete implementationbehind it, using a factory method.

    Speed

    Slow, requires extra indirectionto find the correspondingmethod in the actual class.Modern JVMs are discoveringways to reduce this speedpenalty.

    Fast

    Terseness

    The constant declarations in an

    interface are all presumed publicstatic final, so you may leavethat part out. You can't call anymethods to compute the initialvalues of your constants. Youneed not declare individualmethods of an interfaceabstract. They are all presumedso.

    You can put shared code into an

    abstract class, where you cannotinto an interface. If interfaces wantto share code, you will have to writeother bubblegum to arrange that.You may use methods to computethe initial values of your constantsand variables, both instance andstatic. You must declare all theindividual methods of an abstractclass abstract.

    Addingfunctionality

    If you add a new method to an

    interface, you must track downall implementations of thatinterface in the universe andprovide them with a concreteimplementation of that method.

    If you add a new method to an

    abstract class, you have the optionof providing a defaultimplementation of it. Then allexisting code will continue to workwithout change.

  • 8/8/2019 All Differences in Dot Net

    3/34

    An Abstract class without any implementation just looks like an Interface; however thereare lot of differences than similarities between an Abstract class and an Interface. Let'sexplain both concepts and compare their similarities and differences.

    What is an Abstract Class?

    An abstract class is a special kind of class that cannot be instantiated. So the questionis why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it butcannot be instantiated. The advantage is that it enforces certain hierarchies for all thesubclasses. In simple words, it is a kind of contract that forces all the subclasses tocarry on the same hierarchies or standards.

    What is an Interface?

    An interface is not a class. It is an entity that is defined by the word Interface. An

    interface has no implementation; it only has the signature or in other words, just thedefinition of the methods without the body. As one of the similarities to Abstract class, itis a contract that is used to define hierarchies for all subclasses or it defines specific setof methods and their arguments. The main difference between them is that a class canimplement more than one interface but can only inherit from one abstract class. SinceC# doesnt support multiple inheritance, interfaces are used to implement multipleinheritance.

    Both Together

    When we create an interface, we are basically creating a set of methods without any

    implementation that must be overridden by the implemented classes. The advantage isthat it provides a way for a class to be a part of two classes: one from inheritancehierarchy and one from the interface.

    When we create an abstract class, we are creating a base class that might have one ormore completed methods but at least one or more methods are left uncompleted anddeclared abstract. If all the methods of an abstract class are uncompleted then it issame as an interface. The purpose of an abstract class is to provide a base classdefinition for how a set of derived classes will work and then allow the programmers tofill the implementation in the derived classes.

    There are some similarities and differences between an interface and an abstract classthat I have arranged in a table for easier comparison:

    Feature Interface Abstract class

    Multiple inheritance A class may inheritseveral interfaces.

    A class may inherit onlyone abstract class.

  • 8/8/2019 All Differences in Dot Net

    4/34

    Defaultimplementation

    An interface cannotprovide any code, justthe signature.

    An abstract class canprovide complete,default code and/or justthe details that have tobe overridden.

    Access Modfiers An interface cannothave access modifiers

    for the subs, functions,

    properties etc

    everything is assumed

    as public

    An abstract class cancontain access modifiers

    for the subs, functions,

    properties

    Core VS Peripheral Interfaces are used todefine the peripheralabilities of a class. Inother words bothHuman and Vehicle caninherit from a IMovableinterface.

    An abstract classdefines the core identityof a class and there it isused for objects of thesame type.

    Homogeneity If variousimplementations onlyshare methodsignatures then it isbetter to use Interfaces.

    If variousimplementations are ofthe same kind and usecommon behaviour orstatus then abstractclass is better to use.

    Speed Requires more time tofind the actual method inthe correspondingclasses.

    Fast

    Adding functionality(Versioning)

    If we add a new methodto an Interface then wehave to track down allthe implementations ofthe interface and defineimplementation for thenew method.

    If we add a new methodto an abstract class thenwe have the option ofproviding defaultimplementation andtherefore all the existingcode might workproperly.

    Fields and Constants No fields can be defined

    in interfaces

    An abstract class can

    have fields and

    constrants defined

  • 8/8/2019 All Differences in Dot Net

    5/34

    What is the Difference between Web User Control and Web Custom Control?

    Web User Controls:

    1) Easy to Create

    2) Limited support for consumers who use visual design tool

    3) A seperate copy of the control is required in each

    application.4)Cannot be added to toolbox in Visual Studio.

    5) Good for Static Layout

    Web Custom Controls:

    1) Harder to Create

    2) Full support for consumers

    3) Only a single copy of the control is required in the GAC

    4)Can be added

    5) Good for Dynamic Layout

    What are the basic differences between user controls and custom controls?

    Now that you have a basic idea of what user controls and custom controls are

    and how to create them, let's take a quick look at the differences between

    the two.

    Factors User control Custom control

    Deployment Designed for single-application scenarios

    Deployed in the source form (.ascx) along with the source code of the

    application

    If the same control needs to be used in more than one application, it

    introduces redundancy and maintenance problems Designed so that it canbe used by more than one application

    Deployed either in the application's Bin directory or in the global assembly

    cache

    Distributed easily and without problems associated with redundancy and

    maintenance

    Creation Creation is similar to the way Web Forms pages are created;

    well-suited for rapid application development (RAD) Writing involves lots of

    code because there is no designer support

    Content A much better choice when you need static content within a fixed

    layout, for example, when you make headers and footers More suited for

    when an application requires dynamic content to be displayed; can be reusedacross an application, for example, for a data bound table control with

    dynamic rows

    Design Writing doesn't require much application designing because they are

    authored at design time and mostly contain static data Writing from

    scratch requires a good understanding of the control's life cycle and the

    order in which events execute, which is normally taken care of in user

    controls

  • 8/8/2019 All Differences in Dot Net

    6/34

    Difference between Dataset and DataReader : Points to be consider whilechoosing between the DataSet and DataReader objects

    DataSet object DataReader object

    Read/Write access Read-only access

    Supports multiple tables from different

    databases

    Supports a single table based on a single

    SQL query of one database

    Disconnected mode Connected mode

    Bind to multiple controls Bind to a single control

    Forward and backward scanning of data Forward-only scanning of data

    Slower access to data Faster access to data

    Greater overhead to enable additional

    features

    Lightweight object with very little overhead

    Supported by Visual Studio .NET tools Must be manually coded

    Explain in-proc,out-proc and sql server

    InProc StateServer SQLServer

    Storagelocation

    session kept aslive objects inweb server(aspnet_wp.exe). Use"cookieless"configuration inweb.config to"munge" thesessionId onto

    the URL (solvescookie/domain/path RFCproblems too!)

    session serialized andstored in memoryin a separate process(aspnet_state.exe). StateServer canrun on another machine

    session serialized andstored in SQL server

    Performance

    Performance Fastest, but themore session

    When storing data ofbasic types (e.g.

    When storing data ofbasic types (e.g.

    http://dng-ado.blogspot.com/2007/05/difference-between-dataset-and.htmlhttp://dng-ado.blogspot.com/2007/05/difference-between-dataset-and.htmlhttp://dng-ado.blogspot.com/2007/05/difference-between-dataset-and.htmlhttp://dng-ado.blogspot.com/2007/05/difference-between-dataset-and.html
  • 8/8/2019 All Differences in Dot Net

    7/34

    data, the morememory isconsumed onthe web server,and that can

    affectPerformance.

    string, integer, etc), inone test environment it's15%slower than InProc.However, the cost of

    serialization/deserialization can affectperformance ifyou're storing lots

    of objects. You haveto do performancetesting foryour own scenario.

    string, integer, etc), inone test environment it's25%slower than InProc.Same warning about

    serialization as inStateServer.

    Robustness Session statewill be lost if theworkerprocess(aspnet_wp.exe)recycles, or if theappdomainrestarts. It'sbecause sessionstate is stored inthe memoryspace of anappdomain

    Solve the session stateloss problem inInProc mode. Allows awebfarm to store sessionon a centralserver. Single point offailure at the StateServer.

    Similar to StateServer.Moreover, sessionstate data can survive aSQL server restart, andyou canalso take advantage ofSQL server failovercluster

    Caveats It won't work in

    web garden

    mode, because

    in that mode

    multiple

    aspnet_wp.exe

    will be running

    on the same

    machine. Switch

    to StateServer orSQLServer when

    using web

    garden. Also

    Session_End

    event is

    supported only in

    - In a web farm,make sure youhave the same inall your webservers.

    - Also, make sureyour objects areserializable.

    - For session state

    to be maintainedacross differentweb servers in theweb farm, theApplication Pathof the website(For example\LM\W3SVC\2) in

    - If you specify

    integrated security in the

    connection string (e.g.

    "trusted_connection=true

    ", or "integrated

    security=sspi"), it won't

    work if you also turn on

    impersonation in

    asp.net. Unfortunately,this bug

    isn't reported in KB yet.

    (There is a QFE fix for

    it.)

    - Also, make sure your

    objects are serializable.

  • 8/8/2019 All Differences in Dot Net

    8/34

    InProc mode.the IIS Metabaseshould beidentical in all theweb servers in the

    web farm.

    See KB 312112 for

    details.

    - For session state to be

    maintained across

    different web servers in

    the web farm, the

    Application Path of the

    website (For example

    \LM\W3SVC\2) in the IIS

    Metabase should be

    identical in all the web

    servers in the web farm.

    See KB 325056 for

    details.

    Arraylist and Hashtable

    ArrayList:

    ==============================

    The ArrayList is a collection class that models a dynamic array, whose size increases

    as required when new objects are added to the array.

    Namespace : System.Collections

    Implementing Interfaces : ICollection, IList, ICloneable, IConvertible

    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

    array is the collection same object which is accessed by index or supscript

    Characteristics:

    ==============================i) To store dynamic data use the arraylist class. So it is compact memory usage.

    ii) The search for an item in an arraylist is performed sequentially. So it is slow.

    iii)Type of Access is indexed.

    HashTable:

    ==============================

    http://support.microsoft.com/default.aspx?scid=kb;EN-US;q312112http://support.microsoft.com/default.aspx?scid=kb;EN-US;q325056http://support.microsoft.com/default.aspx?scid=kb;EN-US;q312112http://support.microsoft.com/default.aspx?scid=kb;EN-US;q325056
  • 8/8/2019 All Differences in Dot Net

    9/34

    A HashTable is a collection of key-value pairs implemented using a hash table

    algorithm.

    Namespace : System.Collections

    Implementing Interfaces : ICollection, IDictionary

    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

    hash table we can store different type object like a structure but hastable follows twofields, one is hash key another one is value

    Characteristics:

    ==============================

    i) Search is very fast.ii) HashTables are big and fast.

    iii)High Memory usage.

    iv) Type of Access is using the hash of a key value.

    1) Hash table store data as name,value pair. while in array only value is store.

    2) to access value from hash table, you need to pass name. while in array, to accessvalue , you need to pass index number.

    3) you can store different type of data in hash table, say int,string etc. while in array youcan store only similar type of data.

    ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary

    Off the top of my head:

    Array - represents an old-school memory array - kind of like a alias for a normal type[]array. Can enumerate. Can't grow automatically. I would assume very fast insertion andretriv. speed.

    ArrayList - automatically growing array. Adds more overhead. Can enum., probablyslower than a normal array but still pretty fast. These are used a lot in .NET

    http://stackoverflow.com/questions/128636/net-data-structures-arraylist-list-hashtable-dictionary-sortedlist-sorteddhttp://stackoverflow.com/questions/128636/net-data-structures-arraylist-list-hashtable-dictionary-sortedlist-sortedd
  • 8/8/2019 All Differences in Dot Net

    10/34

    List - one of my favs - can be used with generics, so you can have a strongly typedarray, e.g. List. Other than that, acts very much like ArrayList.

    Hashtable - plain old hashtable. O(1) to O(n) worst case. Can enumerate the value andkeys properties, and do key/val pairs.

    Dictionary - same as above only strongly typed via generics, such as Dictionary

    SortedList - a sorted generic list. Slowed on insertion since it has to figure out where toput things. Can enum., probably the same on retrieval since it doesn't have to resort, butdeletion will be slower than a plain old list.

    I tend to use List and Dictionary all the time - once you start using them strongly typedwith generics, its really hard to go back to the standard non-generic ones.

    There are lots of other data structures too - there's KeyValuePair which you can use todo some interesting things, there's a SortedDictionary which can be useful as well.

    difference ofArrayVsArrayList

    ARRAY ARRAYLIST

    1. Char[] vowel=new Char[]; ArrayList a_list=new ArrayList();

    2. Array is in the System

    namespace

    ArrayList is in the System.Collections

    namespace.3. The capacity of an Array is fixed ArrayList can increase and decrease size

    dynamically

    4. An Array is a collection of similaritems

    ArrayList can hold item of different types

    5. An Array can have multipledimensions

    ArrayList always has exactly one dimension

    1) An array can be of any data type and contain one data type while array list can

    contain any data type in the form of the object.

    2) With array you cannot dynamically increase or decrease the size of array

    dynamically. You must the define the size of the array. You can change the size of

    the array with redim statement but still you have to define type. While with array list

    you can make list of any sizes. When a element or object is added to array list it size

    http://www.google.co.in/url?sa=t&source=web&cd=1&ved=0CBUQFjAA&url=http%3A%2F%2Fwww.dotnetspider.com%2Fforum%2F2954-difference-Array-Vs-ArrayList.aspx&ei=Fjc3TLKCI4WWrAfWqsWwAg&usg=AFQjCNFNOd2J--20icllfCTIj2EcSiiGFAhttp://www.google.co.in/url?sa=t&source=web&cd=1&ved=0CBUQFjAA&url=http%3A%2F%2Fwww.dotnetspider.com%2Fforum%2F2954-difference-Array-Vs-ArrayList.aspx&ei=Fjc3TLKCI4WWrAfWqsWwAg&usg=AFQjCNFNOd2J--20icllfCTIj2EcSiiGFAhttp://www.google.co.in/url?sa=t&source=web&cd=1&ved=0CBUQFjAA&url=http%3A%2F%2Fwww.dotnetspider.com%2Fforum%2F2954-difference-Array-Vs-ArrayList.aspx&ei=Fjc3TLKCI4WWrAfWqsWwAg&usg=AFQjCNFNOd2J--20icllfCTIj2EcSiiGFAhttp://www.google.co.in/url?sa=t&source=web&cd=1&ved=0CBUQFjAA&url=http%3A%2F%2Fwww.dotnetspider.com%2Fforum%2F2954-difference-Array-Vs-ArrayList.aspx&ei=Fjc3TLKCI4WWrAfWqsWwAg&usg=AFQjCNFNOd2J--20icllfCTIj2EcSiiGFAhttp://www.google.co.in/url?sa=t&source=web&cd=1&ved=0CBUQFjAA&url=http%3A%2F%2Fwww.dotnetspider.com%2Fforum%2F2954-difference-Array-Vs-ArrayList.aspx&ei=Fjc3TLKCI4WWrAfWqsWwAg&usg=AFQjCNFNOd2J--20icllfCTIj2EcSiiGFAhttp://www.google.co.in/url?sa=t&source=web&cd=1&ved=0CBUQFjAA&url=http%3A%2F%2Fwww.dotnetspider.com%2Fforum%2F2954-difference-Array-Vs-ArrayList.aspx&ei=Fjc3TLKCI4WWrAfWqsWwAg&usg=AFQjCNFNOd2J--20icllfCTIj2EcSiiGFA
  • 8/8/2019 All Differences in Dot Net

    11/34

  • 8/8/2019 All Differences in Dot Net

    12/34

    Design Pattern : If your classes use unmanaged resources, you need to implement

    both Dispose & Finalize. Dispose() is called by user code, that is, the code that is using

    your class.

    Finalize/Destructor cannot be called by User code, it's called by Garbage Collector

    Finalize : Is a destructor, called by Garbage Collector when the object goes out of

    scope. Implement it when you have unmanaged resources in your code, and want to

    make sure that these resources are freed when the Garbage collection happens.

    Dispose method belongs to IDisposable interface. If you want to release unmanaged

    objects then it is the best to implement IDisposable and override the Dispose method of

    IDisposable interface. Now once your class has exposed the Dispose method it's the

    responsibility of the client to call the Dispose method to do the cleanup.

    .NET Garbage collector does almost all clean up activity for your objects. But

    unmanaged resources ( ex: Windows API created objects, File, Database connection

    objects, COM objects etc) is outside the scope of .NET framework we have to explicitly

    clean our resources. For these types of objects .NET framework provides Objects.

    Finalize method which can be overridden and clean up code for unmanaged resources

    can be put in this section.

    1.Finalize() is called by the runtime

    2.Is a destructor, called by Garbage Collector when the object goes out of scope.

    3.Implement it when you have unmanaged resources in your code, and want to make

    sure that these resources are freed when the Garbage collection happens.

    Dispose : Same purpose as finalize, to free unmanaged resources. However,

    implement this when you are writing a custom class, that will be used by other users.

    Overriding Dispose() provides a way for the user code to free the unmanaged objects in

    your custom class.

    1.Dispose() is called by the user

    2.Same purpose as finalize, to free unmanaged resources. However, implement this

    when you are writing a custom class, that will be used by other users.

    3.Overriding Dispose() provides a way for the user code to free the unmanaged objects

    in your custom class.

  • 8/8/2019 All Differences in Dot Net

    13/34

    As an aside, here's how the GC works:

    The garbage collector keeps track of objects that have Finalize methods, using an

    internal structure called the finalization queue. Each time your application creates an

    object that has a Finalize method, the garbage collector places an entry in the

    finalization queue that points to that object. The finalization queue contains entries for

    all the objects in the managed heap that need to have their finalization code called

    before the garbage collector can reclaim their memory.

    1>CLR uses the Dispose and Finalize methods for performing garbage collection of

    runtime objects of .Net applications.

    2>Clr has a Garbage Collector(GC) which periodically checks for unused and

    unreferenced objects in Heap.It call Finalize() method to free the memory used by suchobjects.

    3>Dispose is another method which is invoked by Garbage Collector to release the

    memory occupied by an object.Dispose method needs to be explicitly called in code for

    removing an object from Heap.

    4>Dispose method can be invoked only by the classes that IDisposable interface.

    Data Structures Array, ArrayList, Generics, List

    data structures are classes that are used to organize data and provide variousoperations upon their data.

    The best way to compare data structures is in how the data structures performancechanges as the amount of data stored increases.

    In the below sample of iterating an array of filenames for a particular extension:

    http://purecode.wordpress.com/2007/12/03/data-structures-array-arraylist-generics-list/http://purecode.wordpress.com/2007/12/03/data-structures-array-arraylist-generics-list/http://purecode.files.wordpress.com/2007/12/image3.pnghttp://purecode.wordpress.com/2007/12/03/data-structures-array-arraylist-generics-list/
  • 8/8/2019 All Differences in Dot Net

    14/34

    To search for a value in an array we need to visit, potentially, every array value, if wehave n + 1 array elements, we might have to perform n + 1 checks. The time it takes tosearch an array is linearly proportional to the number of elements in the array.

    This sort of analysis described here is called asymptotic analysis, as it examines how

    the efficiency of a data structure changes as the data structures size approachesinfinity. The notation commonly used in asymptotic analysis is called big-Oh notation.The big-Oh notation to describe the performance of searching an unsorted array wouldbe denoted as O(n). The large script O is where the terminology big-Oh notation comesfrom, and the n indicates that the number of steps required to search an array growslinearly as the size of the array grows.

    The Array: Linear, Direct Access, Homogeneous Data Structure

    Arrays are one of the simplest and most widely used data structures in computerprograms. Arrays in any programming language all share a few common properties:

    The contents of an array are stored in contiguous memory. All of the elements of an array must be of the same type or of a derived type;

    hence arrays are referred to as homogeneous data structures. Array elements can be directly accessed. With arrays if you know you want to

    access the ith element, you can simply use one line of code: arrayName[i].

    The common operations performed on arrays are:

    Allocation Accessing

    Declare an array: (initially it will have a null value)

    To work with an array we must instantiate it:

    This allocates a contiguous block of memory in the CLR-managed heap large enough tohold the allocationSize number ofarrayTypes. IfarrayType is a value type, thenallocationSize number of unboxed arrayType values are created. IfarrayType is areference type, then allocationSize number ofarrayType references are created.(unfamiliar with the difference between reference and value types and the managedheap versus the stack?)

    http://purecode.wordpress.com/2007/12/03/nets-common-type-system/http://purecode.wordpress.com/2007/12/03/nets-common-type-system/http://purecode.files.wordpress.com/2007/12/image6.pnghttp://purecode.files.wordpress.com/2007/12/image5.pnghttp://purecode.files.wordpress.com/2007/12/image4.pnghttp://purecode.wordpress.com/2007/12/03/nets-common-type-system/http://purecode.wordpress.com/2007/12/03/nets-common-type-system/
  • 8/8/2019 All Differences in Dot Net

    15/34

    The following is an example that highlights these points:

    All arrays in .NET allow their elements to both be read and written to. The syntax foraccessing an array element is:

    http://purecode.files.wordpress.com/2007/12/image8.pnghttp://purecode.files.wordpress.com/2007/12/image7.png
  • 8/8/2019 All Differences in Dot Net

    16/34

    When working with an array, you might need to change the number of elements it holds.To do so, youll need to create a new array instance of the specified size and copy thecontents of the old array into the new, resized array

    Do not use arrays when your application will store large arrays that are searchedfrequently.

    This is a good article on searching an array Efficiently searching a sorted array

    ArrayList : Creating Type-Safe, Performant, Reusable Data Structures

    A flexible data structure design is where the data structure maintains an internal array ofobject instances. Because all types in the .NET Framework are derived from theobject type, the data structure could store any type.

    There is an existing data structure that achieves this: System.Collections.ArrayList

    http://aspnet.4guysfromrolla.com/articles/110602-1.aspxhttp://purecode.files.wordpress.com/2007/12/image10.pnghttp://purecode.files.wordpress.com/2007/12/image9.pnghttp://aspnet.4guysfromrolla.com/articles/110602-1.aspx
  • 8/8/2019 All Differences in Dot Net

    17/34

    The ArrayList maintains an internal object array and provides automatic resizing of thearray as the number of elements added to the ArrayList grows. Because the ArrayListuses an object array, developers can add any typestrings, integers, FileInfo objects,Form instances, anything.

    The below picture shows how an arraylist behaves with the heap/stack andboxing/unboxing

    The ArrayList provides added flexibility over the standard array, this flexibility comes at

    the cost of performance. Because the ArrayList stores an array of objects, when readingthe value from an ArrayList you need to explicitly cast it to the data type being stored inthe specified location.

    Informative: Boxing / Un-boxing this brief intermission I will discuss what boxing / un-boxing is

    In the above example, it is shown how an int value can be converted to an object andback again to an int. This example shows both boxing and un-boxing. When a variable

    http://purecode.files.wordpress.com/2007/12/image12.pnghttp://purecode.files.wordpress.com/2007/12/image11.png
  • 8/8/2019 All Differences in Dot Net

    18/34

    of a value type needs to be converted to a reference type, an object box is allocated tohold the value and the value is copied into the box.

    Un-boxing is just the opposite. When an object box is cast back to its original valuetype, the value is copied out of the box and into the appropriate storage location.

    Value type objects have two representations: an unboxed form and a boxed form.Reference types are always in a boxed form.

    Generics to the Rescue

    typing and performance issues associated with the ArrayList have been remedied in the

    .NET Framework 2.0. Generics allow for a developer creating a data structure to defertype selection.

  • 8/8/2019 All Differences in Dot Net

    19/34

  • 8/8/2019 All Differences in Dot Net

    20/34

    The main advantages of Generics include:

    Type-safety: a developer using the TypeSafeList class can only add elementsthat are of the type or are derived from the type specified. For example, trying toadd a string to the fib TypeSafeList in the example above would result in a

    compile-time error. Performance: Generics remove the need to type check at run-time, and

    eliminate the cost associated with boxing and unboxing. Reusability: Generics break the tight-coupling between a data structure and the

    application for which it was created. This provides a higher degree of reuse fordata structures.

    The List: a Homogeneous, Self-Redimensioning Array

    An array is a pain to maintain, especially if you dont know the initial dimension andsizing. Imagine a wrapper above the array that managed this nuisance for you. .net2.0introduces such a wrapper, LIST which can be found in the namespaceSystem.Collections.Generics.

    The List class contains an internal array and exposes methods and properties that,among other things, allow read and write access to the elements of the internal array. Itis a homogeneous data structure, utilizes Generics.

    Sample List use:

    Conclusion:

    Two of the most common data structures System.Array andSystem.Collections.Generics.List.

    http://purecode.files.wordpress.com/2007/12/image16.png
  • 8/8/2019 All Differences in Dot Net

    21/34

    The array holds a set of homogeneous elements indexed by ordinal value. The actualcontents of an array are laid out as a contiguous block, thereby making reading from orwriting to a specific array element very fast. In addition to the standard array, the .NETFramework Base Class Library offers the List class.

    Like the array, the List is a collection of homogeneous data items. With a List , you dontneed to worry about resizing or capacity limits, and there are numerous List methods forsearching, sorting, and modifying the Lists data. The List class uses Generics toprovide a type-safe, reusable collection data structure.

    Server.Transer and Response.Redirect

    Server.Transer:

    ----------------------

    1: Url will not changed2:Page must be in same server

    3:Avoid server round trip.

    4: Page extension must be .aspx (We cant accsss non aspx pages)

    Response.Redirect

    -------------------

    1: Page URL will change

    2: We can connect resource of different server

    3: Round Trip required. (Means when we request for a page server generate one more

    request page is found in different location)

    4: We can access non aspx page also (Ex .htm, .asp, .aspx etc).

    differences between stored procedure and functions in SQL Server

    1) functions are used for computations where as procedurescan be used for performing business logic

    2) functions MUST return a value, procedures need not be.

    3) you can have DML(insert, update, delete) statements in afunction. But, you cannot call such a function in a SQLquery..eg: suppose, if u have a function that is updating atable.. you can't call that function in any sql query.-select myFunction(field) from sometable; will throw error.

    4) function parameters are always IN, no OUT is possible

  • 8/8/2019 All Differences in Dot Net

    22/34

    Function :

    1. Should return atleast one output parameter.Can return more than one parameter

    using OUT argument.

    2. Parsed and compiled at runtime.

    3.Cannot affect the state of database.

    4.Can be invoked from SQL statement e.g. SELECT.

    5. Functions are mainly used to compute values.

    Procedure:

    1. Doesn't need to return values but can return value.

    2.Stored as a pseudo-code in database i.e. compiled form.

    3.Can affect the state of database using commit etc.

    4.Cannnot be invoked from SQL statements e.g. SELECT.

    5.Procedures are mainly used to process the tasks.

    Difference between user defined function and stored procedure

    Advantages of User Defined Functions

    Before SQL 2000, User Defined Functions (UDFs), were not available. StoredProcedures were often used in their place. When advantages or disadvantages of UserDefined Functions are discussed, the comparison is usually to Stored Procedures.

    One of the advantages of User Defined Functions over Stored Procedures, is the factthat a UDF can be used in a Select, Where, or Case statement. They also can be usedto create joins. In addition, User Defined Functions are simpler to invoke than Stored

    Procedures from inside another SQL statement.

    Disadvantages of User Defined Functions

    User Defined Functions cannot be used to modify base table information. The DMLstatements INSERT, UPDATE, and DELETE cannot be used on base tables. Anotherdisadvantage is that SQL functions that return non-deterministic values are not allowedto be called from inside User Defined Functions. GETDATE is an example of a non-

  • 8/8/2019 All Differences in Dot Net

    23/34

    deterministic function. Every time the function is called, a different value is returned.Therefore, GETDATE cannot be called from inside a UDF you create.

    Types of User Defined Functions

    There are three different types of User Defined Functions. Each type refers to the databeing returned by the function. Scalar functions return a single value. In Line Tablefunctions return a single table variable that was created by a select statement. The finalUDF is a Multi-statement Table Function. This function returns a table variable whosestructure was created by hand, similar to a Create Table statement. It is useful whencomplex data manipulation inside the function is required.

    Scalar UDFs

    Our first User Defined Function will accept a date time, and return only the date portion.Scalar functions return a value. From inside Query Analyzer, enter:

    CREATE FUNCTION dbo.DateOnly(@InDateTime datetime)RETURNSvarchar(10)ASBEGIN DECLARE @MyOutput varchar(10) SET @MyOutput = CONVERT(varchar(10),@InDateTime,101) RETURN @MyOutputEND

    To call our function, execute: SELECT dbo.DateOnly(GETDATE())

    Notice the User Defined Function must be prefaced with the owner name, DBO in thiscase. In addition, GETDATE can be used as the input parameter, but could not be usedinside the function itself. Other built in SQL functions that cannot be used inside a UserDefined Function include: RAND, NEWID, @@CONNCECTIONS, @@TIMETICKS,and @@PACK_SENT. Any built in function that is non-deterministic.

    The statement begins by supplying a function name and input parameter list. In thiscase, a date time value will be passed in. The next line defines the type of data the UDF

    will return. Between the BEGIN and END block is the statement code. Declaring theoutput variable was for clarity only. This function should be shortened to:

    CREATE FUNCTION testDateOnly(@InDateTime datetime)RETURNSvarchar(10)AS

  • 8/8/2019 All Differences in Dot Net

    24/34

    BEGIN RETURN CONVERT(varchar(10),@InDateTime,101)END

    Inline Table UDFs

    These User Defined Functions return a table variable that was created by a singleselect statement. Almost like a simply constructed non-updatable view, but having thebenefit of accepting input parameters.

    This next function looks all the employees in the pubs database that start with a letterthat is passed in as a parameter. In Query Analyzer, enter and run:

    USE pubs

    GOCREATEFUNCTION dbo.LookByFName(@FirstLetter char(1))RETURNSTABLEASRETURNSELECT *FROM employeeWHERE LEFT(fname, 1) = @FirstLetter

    To use the new function, enter:

    SELECT * FROM dbo.LookByFName('A')

    All the rows having a first name starting with A were returned. The return is a TableVariable, not to be confused with a temporary table. Table variables are new in SQL2000. They are a special data type whose scope is limited to the process that declaredit. Table variables are stated to have performance benefits over temporary tables. Noneof my personal testing has found this result though.

    Multi Statement UDFs

    Multi Statement User Defined Functions are very similar to Stored Procedures. They

    both allow complex logic to take place inside the function. There are a number ofrestrictions unique to functions though. The Multi Statement UDF will always return atable variableand only one table variable. There is no way to return multiple result sets.In addition, a User Defined Function cannot call a Stored Procedure from inside itself.They also cannot execute dynamic SQL. Remember also, that UDFs cannot use non-deterministic built in functions. So GETDATE and RAND cannot be used. Error handlingis restricted. RAISERROR and @@ERROR are invalid from inside User DefinedFunctions. Like other programming languages, the purpose of a User Defined Function

  • 8/8/2019 All Differences in Dot Net

    25/34

    is to create a stand-alone code module to be reused over and over by the globalapplication.

    For a Multi Statement test, we will create a modified version of the LookByFNamefunction. This new function will accept the same input parameter. But rather than return

    a table from a simple select, a specific table will be created, and data in it will bemanipulated prior to the return:

    CREATE FUNCTION dbo.multi_test(@FirstLetter char(1))RETURNS @Result TABLE

    (fname varchar(20),hire_date datetime,on_probation char(1))

    AS

    BEGIN INSERT INTO @Result(fname, hire_date)

    SELECT fname, hire_date FROM employee WHERE LEFT(fname, 1) = @FirstLetter

    UPDATE @Result SET on_probation = 'N'

    UPDATE @Result

    SET on_probation = 'Y' WHERE hire_date < '01/01/1991'

    RETURNEND

    To use the new function, execute:

    SELECT * FROM dbo.multi_test('A')

    With the new Multi Statement Function, we can manipulate data like a Stored

    Procedure, but use it in statement areas like a View.

    For example, only specific columns can be returned.

    SELECT fname FROM dbo.multi_test('A')

    The function can also be joined like a view:

  • 8/8/2019 All Differences in Dot Net

    26/34

    SELECT e.lname, f.fnameFROM employee e INNER JOIN dbo.multi_test('A') fON e.fname = f.fname

    Conclusion

    User Defined Functions offer an excellent way to work with code snippets. The mainrequirement is that the function be self-contained. Not being able to use non-deterministic built in functions is a problem, but if it can be worked around, UDFs willprovide you with a programming plus.

    Difference between new and override keyword?

    Answer:

    Let me explain this through code.

    using System;

    using System.Data;

    using System.Text;

    using System.Windows.Forms;

    namespace BaseDerive

    {

    public partial class Form1 : Form

    {

    public Form1()

    {

    InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)

  • 8/8/2019 All Differences in Dot Net

    27/34

    {

    BaseClass b = new BaseClass();

    b.func1();

    DeriveClass d = new DeriveClass();

    d.func1();

    //Calls Base class function 1 as new keyword is used.

    BaseClass bd = new DeriveClass();

    bd.func1();

    //Calls Derived class function 2 as override keyword is used.

    BaseClass bd2 = new DeriveClass();

    bd2.func2();

    }

    }

    public class BaseClass

    {

    public virtual void func1()

    {

  • 8/8/2019 All Differences in Dot Net

    28/34

    MessageBox.Show("Base Class function 1.");

    }

    public virtual void func2()

    {

    MessageBox.Show("Base Class function 2.");

    }

    public void func3()

    {

    MessageBox.Show("Base Class function 3.");

    }

    }

    public class DeriveClass : BaseClass

    {

    public new void func1()

    {

    MessageBox.Show("Derieve Class fuction 1 used new keyword");

    }

    public override void func2()

    {

  • 8/8/2019 All Differences in Dot Net

    29/34

    MessageBox.Show("Derieve Class fuction 2 used override keyword");

    }

    public void func3()

    {

    MessageBox.Show("Derieve Class fuction 3 used override keyword");

    }

    }

    }

    This is a window application so all the code for calling the function through objects iswritten in Form_Load event.As seen in above code, I have declared 2 classes. One works as a Base class andsecond is a derieve class derived from base class.

    Now the difference is

    new: hides the base class function.Override: overrides the base class function.

    BaseClass objB = new DeriveClass();

    If we create object like above notation and make a call to any function which exists inbase class and derive class both, then it will always make a call to function of baseclass. If we have overidden the method in derive class then it wlll call the derive classfunction.

    For example

    objB.func1(); //Calls the base class function. (In case of new keyword)

    objB.func2(); //Calls the derive class function. (Override)

  • 8/8/2019 All Differences in Dot Net

    30/34

    objB.func3(); //Calls the base class function.(Same prototype in both the class.)

    Note:// This will throw a compile time error. (Casting is required.)

    DeriveClass objB = new BaseClass();

    //This will throw run time error. (Unable to cast)DeriveClass objB = (DeriveClass) new BaseClass();

    Difference between shadow and override?

    I find this table from MSDN to be useful to explain differences between shadowing andoverriding: The main constraint on overriding is that it needs permission from the baseclass with the 'overridable' keyword. Shadowing does not require permission of baseclass.

    Criterion Shadowing Overriding

    Purpose Protecting against asubsequent base classmodificationintroducing a memberyou have alreadydefined in your derivedclass

    Achieving polymorphism by defining adifferent implementation of a procedure orproperty with the same calling sequence

    Redefinedelement

    Any declared elementtype

    Only a procedure (Function orSub) orproperty

    Redefiningelement

    Any declared elementtype

    Only a procedure or property with theidentical calling sequence1

    Accessibility Any accessibility Cannot expand the accessibility of overridden

    element (for example cannot overrideProtected with Public)

    Readability andwritability

    Any combination Cannot change readability or writability ofoverridden property

    Keyword usage Shadowsrecommended inderived class;Shadows assumed if

    Overridable required in base class;Overrides required in derived class

  • 8/8/2019 All Differences in Dot Net

    31/34

  • 8/8/2019 All Differences in Dot Net

    32/34

    b.bar(); // Prints B::barreturn 0;

    }}

    virtual / override tells the compiler that the two methods are related and that in somecircumstances when you would think you are calling the first (virtual) method it's actuallycorrect to call the second (overridden) method instead. This is the foundation ofpolymorphism.

    (new SubClass() as BaseClass).VirtualFoo()

    Will call the SubClass's overriden VirtualFoo() method.

    new tells the compiler that you are adding a method to a derived class with the same

    name as a method in the base class, but they have no relationship to each other.

    (new SubClass() as BaseClass).NewBar()

    Will call the BaseClass's NewBar() method, whereas:

    (new SubClass()).NewBar()

    Will call the SubClass's NewBar() method.

    Please try this for difference of override and new keyword

    using System;using System.Collections.Generic;using System.Text;

    namespace ConsoleApplication2{

    public class ChildOne{

    public virtual int Add(){

    return 1;

  • 8/8/2019 All Differences in Dot Net

    33/34

  • 8/8/2019 All Differences in Dot Net

    34/34

    }}

    Difference between override and new

    overridepublicclassBase{

    publicvirtualvoid SomeMethod(){

    //print base}

    }publicclass Derived : Base{

    publicoverridevoid SomeMethod(){

    //print child}

    }//...Base b = new Derived();b.SomeMethod();

    newpublicclassBase{

    public virtualvoid SomeOtherMethod(){

    //print base}

    }publicclass Derived : Base{ publicnew void SomeOtherMethod()

    { //print child

    }}//...Base b = new Derived();Derived d = new Derived();b.SomeOtherMethod();d.SomeOtherMethod();

    Out put Out put

    Child base

    Child

    So whats the matter:

    Virtual keyword makes the method on the base type prone to any derived ones overrideit by writing override keyword before it

    So when calling it from the parent object, parent object looks for if any overrides exists

    to implement it and eliminates the current virtual method code

    But the new keyword make a new version from the method actually its a new one at all;

    So when calling it on the parent object, although it was initialized by a child one, butnow this method (public new void SomeOtherMethod()) is another one totally so theparent object implements its own method

    http://blog.flair-systems.com/2010/05/c-fastfood-difference-between-override.htmlhttp://blog.flair-systems.com/2010/05/c-fastfood-difference-between-override.html