C#: Creates two string-objects with different value
C# Sharp String: Exercise-39 with Solution
Write a C# Sharp program to create two string objects with different values.
When it calls the Copy method to assign the first value to the second string, the output indicates that the strings represent different object references. However, their values are now equal. On the other hand, when the first string is assigned to the second string, the two strings have identical values. This is because they represent the same object reference.
Sample Solution:-
C# Sharp Code:
using System;
class Example39
{
public static void Main()
{
string s1 = "JAVA"; // Original string s1
string s2 = "Python"; // String s2
Console.WriteLine("s1 = '{0}'", s1); // Display s1 value
Console.WriteLine("s2 = '{0}'", s2); // Display s2 value
Console.WriteLine("\nAfter String.Copy..."); // Display message for String.Copy
s2 = String.Copy(s1); // Copy contents of s1 to s2
Console.WriteLine("s1 = '{0}'", s1); // Display updated s1 value
Console.WriteLine("s2 = '{0}'", s2); // Display updated s2 value
Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(s1, s2)); // Check reference equality
Console.WriteLine("Equals: {0}", Object.Equals(s1, s2)); // Check value equality
Console.WriteLine("\nAfter Assignment..."); // Display message after assignment
s2 = s1; // Assign s1 to s2
Console.WriteLine("s1 = '{0}'", s1); // Display updated s1 value
Console.WriteLine("s2 = '{0}'", s2); // Display updated s2 value
Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(s1, s2)); // Check reference equality
Console.WriteLine("Equals: {0}", Object.Equals(s1, s2)); // Check value equality
}
}
Sample Output:
s1 = 'JAVA' s2 = 'Python' After String.Copy... s1 = 'JAVA' s2 = 'JAVA' ReferenceEquals: False Equals: True After Assignment... s1 = 'JAVA' s2 = 'JAVA' ReferenceEquals: True Equals: True
Flowchart :
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to determine whether the string "birds" is a substring of a familiar.
Next: Write a C# Sharp program to demonstrates the CopyTo method.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/csharp-exercises/string/csharp-string-exercise-39.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics