16
DOTNET Programming Concepts Difference FAQs-1 1.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 than Hashtable because If we want to find something in a arraylist we have to go through each value in arraylist. Retrieving by key in Hashtable is faster than retrieving in Arraylist because If we want to find something in a hashtable we dont have to go through each value in hashtable, instead search for key values and is faster. 2.Difference between Hash Table and Arrays S.No Hash Table Array 1 Hash table stores data as name,value pair. Array stores only value 2 To access value from hash table, we need to pass name. In array, to access value , we need to pass index number. 3 We can store different type of data in hash table, say int,string etc. In array ,we can store only similar type of data. 3.Difference between Dictionary and Hashtable S.No Dictionary Hashtable 1 Dictionary is a generic type Hashtable is not generic type. 2 In Dictionary we need to specify the types of both the key and the corresponding value.The value represents the actual object stored and the key represents a means to identify a particular object. Hashtable is a collection of name/value pairs that are organised on the basis of hash code of the key being specified. 3 In Dictionary public static members are type safe but any Hashtable is thread safe for use by multiple reader threads and a single

Dotnet Programming Concepts Difference FAQS Compiled-1

Embed Size (px)

DESCRIPTION

This is compiled version(part-1) of Dotnet Programming Concepts Difference FAQS

Citation preview

Page 1: Dotnet Programming Concepts Difference FAQS Compiled-1

DOTNET Programming Concepts Difference FAQs-1

1.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 than Hashtable because If we want to find something in a arraylist we have to go through each value in arraylist.

Retrieving by key in Hashtable is faster than retrieving in Arraylist because If we want to find something in a hashtable we dont have to go through each value in hashtable, instead search for key values and is faster.

2.Difference between Hash Table and Arrays

S.No Hash Table Array

1 Hash table stores data as name,value pair.

Array stores only value

2 To access value from hash table, we need to pass name.

In array, to access value , we need to pass index number.

3 We can store different type of data in hash table, say int,string etc.

In array ,we can store only similartype of data.

3.Difference between Dictionary and Hashtable

S.No Dictionary Hashtable

1 Dictionary is a generic type Hashtable is not generic type.

2 In Dictionary we need to specify the types of both the key and the corresponding value.The value represents the actual object stored and the key represents a means to identify a particular object.

Hashtable is a collection of name/value pairs that are organised on the basis of hash code of the key being specified.

3 In Dictionary public static members are type safe but any

Hashtable is thread safe for use by multiple reader threads and a single

Page 2: Dotnet Programming Concepts Difference FAQS Compiled-1

instance members are not type safe.

writing thread.

4 We cannot use Dictionary with Web Services The reason is no web service standard supports generic standard.

We can use Hashtable withWeb Services

5 Dictionary is aster than Hashtable because boxing is not required.

It is slower than dictionary because to retrieve a value we must cast it as its actual type, because it will be returned via object reference.

4.Difference between array and stack

S.No Array Stack

1 An array can be multi-dimensional

Stack is strictly one-dimensional

2 An array allows direct access to any of its elements

With a stack, only the 'top' element is directly accessible; to access other elements of a stack, we must go through them in order, until we get to the one we want

5.Difference between Stack and Heap

S.No Stack Heap

1 Memory will be allocated at the compile time.

Memory will be allocated at the run time.

2 Here the memory is allocated by the compiler.

Here the memory is allocated by the user.

3 Memory will be allocated only in sequential locations.

Memory will be allocated in sequential locations and non- sequential locations.

4 The memory will also be deleted by the compiler.

The memory must be deleted explicitly by the user.

5 There is lot of chance of memory wastage.

There is no chance of memory wastage if the memory is handled perfectly.

Page 3: Dotnet Programming Concepts Difference FAQS Compiled-1

6.Difference between Array and ArrayList

S.No Array ArrayList

1 They are fixed length. They are resizable and variable length

2 They are compiled strong type collection.

They are flexible and can accommodate any data types.

3 Because arrays are of fixed size and strong type collection performance is faster.

In arraylist lots of boxing and unboxing are done there for its performance is slower.

4 Array is in the System namespace

ArrayList is in the System.Collections namespace.

5 Ex:Char[] vowel=new Char[]; Ex:ArrayList a_list=new ArrayList();

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/dotnet-programming-concepts-difference.html

Dotnet Programming Concepts Difference FAQs-2

1.Difference between for and foreach loop

S.No For loop Foreach loop

1 In case of for the variable of the loop is always be int only.

In case of Foreach the variable of the loop while be same as the type of values under the array.

2 The For loop executes the statement or block of statements repeatedly until specified expression evaluates to false.

The Foreach statement repeats a group of embedded statements for each element in an array or an object collection.

3 There is need to specify the loop bounds(Minimum, Maximum).

We do not need to specify the loop bounds minimum or maximum.

4 example: using sytem; class class1 { static void Main() { int j=0; for(int i=0; i<=10;i++) { j=j+1;

example: using sytem; class class1 { static void Main() { int j=0; int[] arr=new int[] {0,3,5,2,55,34,643,42,23}; foreach(int i in arr)

Page 4: Dotnet Programming Concepts Difference FAQS Compiled-1

} 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 specific type is called co-variance.If B is derived from A and B relates to A, then we can assign A to B. Like A=B. This is Covariance.

Converting from a more specific type to a broader type is called contra-variance. If B is derived from A and B relates to A, then we can assign B to A. Like B= A. This is Contravariance.

2 Co-variance is guaranteed to work without any loss of information during conversion. So, most languages also provide facility for implicit conversion.

e.g. Assuming dog and cat inherits from animal, when you convert from animal type to dog or cat, it is called co-variance.

Contra-variance on the other hand is not guaranteed to work without loss of data. As such an explicit cast is required.

e.g. Converting from cat or dog to animal is called contra-variance, because not all features (properties/methods) of cat or dog is present in animal.

3 Example:

class Fruit { }

class Mango : Fruit { }

class Program

{

Page 5: Dotnet Programming Concepts Difference FAQS Compiled-1

delegate T Func();

delegate void Action(T a);

static void Main(string[] args)

{

// Covariance

Func mango = () => new Mango();

Func fruit = mango;

// Contravariance

Action fr = (frt) =>

{ Console.WriteLine(frt); };

Action 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.

Page 6: Dotnet Programming Concepts Difference FAQS Compiled-1

3.Difference between IList and IEnumerable

S.No IList IEnumerable

1 IList is used to access an element in a specific position/index in a list.

IEnumerable is a forward only collection, it can not move backward and between the items.

2 IList is useful when we want to Add or remove items from the list.

IEnumerable does not support add or remove items from the list.

3 IList can find out the no of elements in the collection without iterating the collection.

Using IEnumerable we can find out the no of elements in the collection after iterating the collection.

4 IList does not support filtering.

IEnumerable supports filtering.

4.Difference between IEnumerable and IQueryable

S.No IEnumerable IQueryable

1 IEnumerable exists in System.Collections Namespace.

IQueryable exists in System.Linq Namespace.

2 IEnumerable is best to query data from in-memory collections like List, Array etc.

IQueryable is best to query data from out-memory (like remote database, service) collections.

3 While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.

While query data from database, IEnumerable execute select query on server side with all filters.

4 IEnumerable is suitable for LINQ to Object and LINQ to XML queries.

IQueryable is suitable for LINQ to SQL queries.

5 IEnumerable does not supports custom query.

IQueryable supports custom query using CreateQuery and Execute methods.

6 IEnumerable does not support lazy loading. Hence not suitable for paging like scenarios.

IQueryable support lazy loading. Hence it is suitable for paging like scenarios.

7 Extension methods supports by IEnumerable takes functional objects.

Extension methods supports by IEnumerable takes expression objects means

Page 7: Dotnet Programming Concepts Difference FAQS Compiled-1

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

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 interface that provides an abstraction for

IEnumerator provides two abstract methods and a property to pull a particular

Page 8: Dotnet Programming Concepts Difference FAQS Compiled-1

looping over elements. In addition to providing foreach support, it allows us to tap into the useful extension methods in the System.Linq namespace, opening up a lot of advanced functionality The IEnumerable interface contains an abstract member function called GetEnumerator() and return an interface IEnumerator on any success call.

element in a collection. And they are Reset(), MoveNext() and Current The signature of IEnumerator members is as follows: void Reset() : Sets the enumerator to its initial position, which is before the first element in the collection. bool MoveNext() : Advances the enumerator to the next element of the collection. object Current : Gets the current element in the collection

2 IEnumerable does not remember the cursor state i.e currently row which is iterating through

IEnumerator does remember the cursor state

3 IEnumerable is useful when we have only iterate the value

IEnumerator is useful when we have to pass the iterator as parameter and has to remember the value

Reference: http://onlydifferencefaqs.blogspot.in/2012/07/dotnet-programming-concepts-difference.html

DOTNET Programming Concepts Difference FAQs-3

1.Difference between directCast and ctype in .NET

S.No DirectCast ctype

1 DirectCast is generally used to cast reference types.

Ctype is generally used to cast value types.

2 When you perform DirectCast on arguments that don't match then it will throw InvalidCastException.

Exceptions are not thrown while using ctype.

3 If you use DirectCast, you cannot convert object of one type into another. Type of the object at runtime should be same as the type that is specified in DirectCast. Consider the following example:Dim sampleNum as Integer

Ctype can cast object of one type into another if the conversion is valid. Consider the following example:Dim sampleNum as IntegerDim sampleString as StringsampleNum = 100sampleString = CType(sampleNum, String)

Page 9: Dotnet Programming Concepts Difference FAQS Compiled-1

Dim sampleString as StringsampleNum = 100sampleString = DirectCast(sampleNum, String)This code will not work because the runtime type of sampleNum is Integer, which is different from the specified type String.

This code is legal and the Integer 100 is now converted to a string.

4 To perform DirectCast between two different classes, the classes should have a relationship between them.

To perform ctype between two different value types, no relationship between them is required. If the conversion is legal then it will be performed.

5 Performance of DirectCast is better than ctype. This is because no runtime helper routines of VB.NET are used for casting.

Performance wise, ctype is slow when compared to DirectCast. This is because ctype casting requires execution of runtime helper routines of VB.NET.

6 DirectCast is portable across many languages since it is not very specific to VB.NET

Ctype is specific to VB.NET and it is not portable.

2.Difference between Convert.ToString() and object.ToString()

S.No Convert.ToString() object.ToString()

1 Convert.ToString(object) does not give any error in case of object value is null

object.ToString() give run time error if object value is null

Example:

object obj=null; string str=obj.ToTsirng(); //it will give run time error string str1=Convert.ToString(obj); // it will run, not give any error

3.Difference between String.Equals(string1,string2) and string1.Equals(string2)

S.No String.Equals(string1,string2)

string1.Equals(string2)

1 String.Equals(string1,string2) will not throw any error if any of strings value is null

If any of strings value is null, string1.Equals(string2) will throw runtime error

Example: try { string str1 = null;

Page 10: Dotnet Programming Concepts Difference FAQS Compiled-1

string str2 = "abc"; bool chk; chk = str1.Equals(str2); // will give runtime error chk = String.Equals(str1, str2); //will not give any error } catch (Exception ex) { MessageBox.Show(ex.Message); }

4.Difference between catch(Exception objex) and catch() block

S.No catch(Exception objex) catch() block

1 catch(Exception objEx) will catch only .net compliance exceptions .

catch() will catch all types of exception i.e., both non-compliance and .net compliance exceptions

5.Difference between "Convert" class and "Parse()" method

S.No Convert Class Parse() method

1 The Convert class is used to convert any value from any data type to another data type. This class consist of different methods for making conversions.

The Parse method is used to convert only one string value to any other data type. Every data type is consisting of parse() method.

2 Example: 1) char ch = Convert.ToChar("x"); -> string to character 2) float f = Convert.ToSingle(45); -> int to float 3) int x = Convert.ToInt(4.5f); -> float to int

Example: 1) int x = int.Parse("600"); -> string to int 2) char ch = char.Parse("dnf"); -> string to character

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/dotnet-programming-concepts-difference_8.html

Difference Between ref and out parameters

Difference between Ref and Out parameters

S.No Ref Out

1 Ref parameters are both input and output - a value is passed into a method and a new value is passed out

Out parameters are only for output - a value is passed out of a method

Page 11: Dotnet Programming Concepts Difference FAQS Compiled-1

2 An argument passed to ref parameter must be initialized

out argument does not have to be explicitly initialized.

3 Ref parameter may be written to before returning from method

Out parameter must be written to before returning from method

4 Ref parameter may be referenced inside method before being written to

Out parameter may not be referenced inside method before being written to

Example for ref parameter :

class Program{static void M1(ref int i){i = 1;i += 1;}

static void Main(string[] args){int j=0; //AssignedM1(ref j);Console.Write(j);Console.Read();}}

The output is same: 2, but we have to assign the variable before used otherwise we will get an error.

Example for out parameter :

class Program{static void M1(out int i){i = 1;i += 1;}

static void Main(string[] args){int j; //Not assignedM1(out j);Console.Write(j);Console.Read();}}

Page 12: Dotnet Programming Concepts Difference FAQS Compiled-1

}

The output is : 2

Summary:

1. Both are treated differently @ runtime but same in the compile time, so can’t be overloaded.2. Both are passed by references except ‘ref’ requires that the variable to be initialized before passed.

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/difference-between-ref-and-out.html

Difference between Checked and Unchecked keywords in .NET

Difference between Checked and Unchecked keywords in .NET

S.No Checked keyword Unchecked keyword

1 The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.i.e., Checked Key word is used to enforce the compiler to check the buffer overflow while operating arithmetic operators.

The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.i.e.,Unchecked Keyword is used to enforce the compiler to do not check that is there any buffer overflow or Not.

2 If there is any Buffer overflow code will throw exception.

If here any Buffer overflow is occurred it will just truncate the value but not throw exception

Example for Checked keyword:

static void Main(string[] args){int _value1 = 1500056564;int _value2 = 1200046565;checked{// this Code will give exception BuferOverflowSystem.Console.WriteLine(_value1 * _value2); System.Console.Read();}}

Example for Unchecked keyword:

static void Main(string[] args){int _value1 = 1500056564;

Page 13: Dotnet Programming Concepts Difference FAQS Compiled-1

int _value2 = 1200046565;unchecked{// This Code will Not Give ExceptionSystem.Console.WriteLine(_value1 * _value2); System.Console.Read();}}

Note: Both the Checked and Unchecked keywords control whether or not an exception will be thrown when an operation causes a number to overflow.

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/difference-between-checked-and.html

Difference between Clone and CopyTo methods in .NET

Difference between Clone and CopyTo methods in .NET

S.No Clone CopyTo

1 Clone method returns a new array containing all elements copied from the array on which clone method is called.

CopyTo method copies elements of the array into an existing array. Elements will be copied into a specific index and its increments.

2 The array size of the destination array need not be mentioned.

Array size of the destination array has to be declared before triggering copyTo method.

3 If the array size declared is smaller to fit in elements, the array size will automatically grow based on the number of elements that are getting copied.

Array size should be large enough to fit both existing array elements and the elements to be copied. If the size is smaller than the actual number of elements, then you will get the following error while performing CopyTo:"Destination array was not long enough. Check destIndex and length, and the array's lower bounds."

Here is an example of Clone method:

class sampleClass{public static void Main() {int[] array1 = new int[] {10,20,30};int[] array2 = array1.Clone() as int[];for(int i=0;iConsole.Write(array2[i]+" ");}}

Page 14: Dotnet Programming Concepts Difference FAQS Compiled-1

}Output of this code will be:10 20 30

Here is an example of CopyTo method: class sampleClass{public static void Main() {int[] array1 = new int[] {10,20,30};int[] array2 = new int[array1.Length];array1.CopyTo(array2,0);for(int i=0;iConsole.Write(array2[i]+" ");}}}Output of this code will be:10 20 30

Note: Both the Clone and CopyTo methods belong to System.Array namespace.

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/difference-between-clone-and-copyto.html

Difference between Int and Int32

Difference between Int and Int32

S.No Int Int32

1 Int is a datatype which has following three types,Int16 Int32 Int64

Int32 is the alias of Int

Summary:

Both int and int32 are same . So there is no real difference between them .To make it user friendly ,int32 is given alias name as int.

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/difference-between-int-and-int32.html

Difference between Constructor and Destructor in C#

Difference between Constructor and Destructor in C#

S.No Constructor Destructor

1 It is a special type of method which will be executed

It will be executed automatically while destroying object

Page 15: Dotnet Programming Concepts Difference FAQS Compiled-1

automatically while creating an object

2 Constructor name must be same as class name with out return type

The name of destructor must be same as class name with a ~(tilde) prefix and with out return type and with out access specifiers

3 Syntax:public class_name() { }

Syntax:~class_name() { }

4 These are overloadable These are not overloadable

5 These are used to initialize the variables to open files or database connection etc

It is used to de-allocate the memory

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/difference-between-constructor-and.html

Difference between Boxing and Unboxing in C#

Difference between Boxing and Unboxing in C#

S.No Boxing Unboxing

1 Meaning:Boxing is the process of converting a value type to the reference type.

Meaning:Unboxing is the process of converting a reference type to value type.

2 Type of Conversion:Implicit Conversion

Type of Conversion:Explicit Conversion

3 Example:int i = 1;object obj = i; //boxing

Example:object obj = 123;i = (int)obj ; // unboxing

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/difference-between-boxing-and-unboxing.html

Difference between Implicit Conversion and Explicit Conversion

Difference between Implicit Conversion and Explicit Conversion

S.No Implicit Conversion Explicit Conversion

1 Implicit Conversion perform automatically in VB.NET, that

In some cases we have to perform conversions , that is the compiler

Page 16: Dotnet Programming Concepts Difference FAQS Compiled-1

is the compiler is taking care of the conversion and therefore does not require any special syntax in the source code.

does not automatically convert a type to another . These type of conversion is called Explicit conversion . An explicit conversion uses a type conversion keyword, eg.CType ,CInt ,CStr etc., With these conversion keywords we have to perform the Explicit Conversion

Example for Implicit Conversion:

Dim K As IntegerDim Q As Double' ...K = 432 ' Integer widens to Double, so Option Strict can be On.Q = K

In the above example, Visual Basic .NET implicitly converts the value of K to single-precision floating point before assigning it to Q.

Example for Explicit Conversion:

Dim K As IntegerDim Q As Double' ...K = 432 ' Integer widens to Double, so Option Strict can be On.Q = K

Q = Math.Sqrt(Q) ' Q had been assigned the value 432 from K.K = CInt(Q) ' K now has the value 21 (rounded square root of 432).

In the above example, the CInt keyword converts the value of Q back to an integer before it is assigned to K

Reference: http://onlydifferencefaqs.blogspot.in/2012/08/difference-between-implicit-conversion.html