Thursday 24 January 2013

we can not create multiple instances for string in c# .net

Hi All,

Now i am going to discuss a uncommon thing with you, which i saw during development.

All you know that in C# .Net we have a method as

public static bool ReferenceEquals(object objA, object objB)
// Summary:
        //     Determines whether the specified System.Object instances are the same 

                 instance.
        //
        // Parameters:
        //   objA:
        //     The first System.Object to compare.
        //
        //   objB:
        //     The second System.Object to compare.
        //
        // Returns:
        //     true if objA is the same instance as objB or if both are null references;
        //     otherwise, false.


To check this method i wrote a program as:

        int i1=0;
        int i2 = 0;
        Console.WriteLine(object.ReferenceEquals(i1, i2));
        //  Output: False (Nice)

        float f1 = 0;
        float f2 = 0;
        Console.WriteLine(object.ReferenceEquals(f1, f2));
        //  Output: False (Great)

        DateTime d1 = new DateTime();
        DateTime d2 = new DateTime();
        Console.WriteLine(object.ReferenceEquals(d1, d2));
        //  Output: False (Awesome)

        string s1 = string.Empty;
        string s2 = string.Empty;
        Console.WriteLine(object.ReferenceEquals(s1, s2)); 

        //  Output: True(What? how is it possible?)

In case of string's different instances comparison it gives me True, ideally it should give me False because both the instances are not same.

Can any one help me to short out this logic.

Waiting for reply.