C# Programming - Strings - Discussion

Discussion Forum : Strings - General Questions (Q.No. 3)
3.
Which of the following statements will correctly copy the contents of one string into another ?
String s1 = "String";
String s2; 
s2 = s1;
String s1 = "String" ; 
String s2;
s2 = String.Concat(s1, s2);
String s1 = "String"; 
String s2;
s2 = String.Copy(s1);
String s1 = "String"; 
String s2;
s2 = s1.Replace();
String s1 = "String"; 
String s2;
s2 = s2.StringCopy(s1);
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
14 comments Page 1 of 2.

Mark said:   1 decade ago
String s1 = "String";
String s2;
s2 = String.Copy(s1);
//is the right answer!!

Vishnu said:   1 decade ago
String s1 = "String";
String s2;
s2 = s1;
//it is also right

Neeraj said:   1 decade ago
Mark is right. Because in s2=s1 giving the reference of s1 to s2.

Amit Gupta said:   1 decade ago
Why not first is right?

Zeel said:   1 decade ago
Yes exactly this is also right.

String s1 = "String";
String s2;
s2 = s1;

//It is also right.

Mahi said:   1 decade ago
Can't find the difference.

Can anyone tell clearly.

Sami said:   1 decade ago
When s1="string"; here a reference points to the "string". and when.

s2=s1; here s2 also points to the "string". and same is the case.

When s2 = String.Copy (s1) ;. So why 1st is not right. Can any please tell the difference?

Nichholas Mahbouby said:   1 decade ago
s1 = s2 will result in 2 variables that reference the same object.

s2 = string.Copy(s1) will result in 2 variables that reference different objects containing the same value. Console.Write(object.ReferenceEquals(s1, s2)) will output "False".

Max said:   1 decade ago
Desription:

Acc. to question we need to copy the contents of one string into another.

Solution:-

Option-1 : Incorrect, String s1 = "String" when executed will create a "String" object. s2 = s1 doesn't copies the content rather it passes its reference to variable s2. Only 1 Object is created both s1 and s2 referring same object.

Option-2 : Obviously Incorrect answer, Reason Strings are immutable

Option-3 : Correct, because here we are only copying the content , so in end we will have 2 objects . By value they are same but by reference they are different.

Option-4 : No overload for method 'Replace' takes '0' arguments.

Option-5 : Type 'string' does not contain a definition for 'StringCopy' and no extension method 'StringCopy' of type 'string' could be found.

Thank You :).

Vijay said:   1 decade ago
If you refer to the first question in strings, it clearly mentions strings are immutable and CLR optimizes memory by interning same strings into one.

If Option 3 is correct, does it not defeat the above fact ?


Post your comments here:

Your comments will be displayed after verification.