Friday, April 9, 2010

Interview Questions

What is the difference between a.Equals(b) and a == b?

What is the difference between a.Equals(b) and a == b?

 

Answer:
For value types : “==” and Equals() works same way : Compare two objects by VALUE
Example:
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True

For reference types : both works differently :
“==” compares reference – returns true if and only if both references point to the SAME object while
"Equals" method compares object by VALUE and it will return true if the references refers object which are equivalent
Example:
StringBuilder sb1 = new StringBuilder(“Mahesh”);
StringBuilder sb2 = new StringBuilder(“Mahesh”);
sb1 == sb2 > False
sb1.Equals(sb2) > True

But now look at following issue:
String s1 = “Mahesh”;
String s2 = “Mahesh”;
In above case the results will be,
s1 == s2 > True
s1.Equals(s2) > True
String is actually reference type : its a sequence of “Char” and its also immutable but as you saw above, it will behave like Value Types in this case.
Exceptions are always there ;)

Now another interesting case:
int i = 0;
byte b = 0;
i == b > True
i.Equals(b) > False
So, it means Equals method compare not only value but it compares TYPE also in Value Types.

Recommendation :
For value types: use “==”
For reference types: use Equals method.

What is the use of unsafe keyword in C#?

What is the use of unsafe keyword in C#?

 

Answer:
In C# the value can be directly referenced to a variable, so there is no need of pointer.

Use of pointer sometime crashes the application. But C# supports pointer, that means we can use pointer in C#.

The use of pointer in C# is defined as a unsafe code.

So if we want to use pointer in C# the pointer must be present in the body of unsafe declaration.

But pointer does not come under garbage collection.

Example:-

unsafe
{
int a, *b;
a = 25;
b = &a;
Console.WriteLine("b= {0}",b);//returns b= 25
}

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code