Skip to content

Doubt in c# basic

Jatin Kumar

Asked Jun 17, 2009, 5:07 AM EDT1 answer
Share
LinkedInX
class s
{
static void Main()
{
string d="Hello";
string e=string.Copy(d);
Console.WriteLine(d==e);
Console.WriteLine((object)d==(object)e);
}
}
o/p:
True
False

BUT

class s
{
static void Main()
{
object a = "hello";
object b = "hello";
Console.WriteLine(a==b);
}
}
o/p:
True.

In the previous case when the result of the comparison is false, we compare two strings and as string is a predefined reference type...so d result should evaluate to true and not false.

Please clear my doubt.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    when you say d==e it will always look for contents and thus it is printing "True" in both cases; though in 2nd eg you have declared it as Object.
    BUT in 1st eg. the line (Object)d==(Object)e will compare the reference to string object as you r casting it to super class Object so naturally as both the string objects are dissimilar it wil print "False".
    string.Copy() method creates new instance of a string object so last line  of your 1st eg is giving you False as you are comparing object ref. which is not true in 2nd case where you are just checking onject's content/value it holding.

     
    0