What is the difference between string and System.String in C#?
A string represents a sequence of characters. There are different ways to create strings, e.g., string and System.String. In this Answer, we’ll learn the difference between them.
Below are the key differences between string and System.String in C#:
The | The |
The | The |
The | The |
The Syntax of | The |
C# has a few overloaded operators for performing operations on strings. For example, the | The |
String class and string keyword are equivalent and refer to the same thing.
Example
The following code snippet will further clarify the differences between string and String.
using System; // for using String classclass HelloWorld{static void Main(){// not initialized, has value nullstring str1;// initialized to a literalstr1 = "Hello World!";String str2 = "Hello World!";// copy of existing stringString str3 = String.Copy(str2);string str4 = str1;System.Console.WriteLine(str1 == str2); // displays 'True'System.Console.WriteLine(string.Equals(str3, str4)); // dispalys 'True'}}
Explanation
-
Line 8: We initialize a
stringtype variable calledstr1. It’s value is null by default. -
Line 10: We assign the value,
"Hello World!", to thestr1string. -
Line 12: We use the
System.Stringclass to define a string instance.
We can use either of the below syntaxes to declare string variables:
string str1 = "Hello World!";
String str2 = "Hello World!";
Both variables refer to an instance of the System.String class with string value "Hello World!".
-
Line 14: We create a copy of an instance by explicitly calling
Copystatic method ofSystem.Stringon an existing string instance that has already been assigned a value. -
Line 15:
str3is assigned tostr4. Both the variables refer to an instance of theSystem.Stringclass with string value"Hello World!".
The equality operator == returns True if both the strings are equal. If not, it returns False.
Equals(String, String) performs the equality check and returns true if two string instances have the same value. If not, it returns false.