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 string keyword

The System.String class

The string is a keyword in C#

The String is a class in C#


The string keyword is an alias for the String class. It doesn’t require usage of any using statements

The String class is part of System namespace. To use it, we need to provide using System statement

The string keyword is used to create a String object.

Syntax of string: string str1 = "Hello World!";

The String class is also used to create a String object. Syntax of String: String str2 = "Hello World!";

C# has a few overloaded operators for performing operations on strings. For example, the [] operator is used to access characters of a string, and the + operator is used to perform concatenation of strings.

The String class contains many useful methods for instantiating, processing, and comparing strings, such as EqualsContainsStartsWithEndsWithIndexOf more.



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 class
class HelloWorld
{
static void Main()
{
// not initialized, has value null
string str1;
// initialized to a literal
str1 = "Hello World!";
String str2 = "Hello World!";
// copy of existing string
String 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 string type variable called str1. It’s value is null by default.

  • Line 10: We assign the value, "Hello World!", to the str1 string.

  • Line 12: We use the System.String class 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 Copy static method of System.String on an existing string instance that has already been assigned a value.

  • Line 15: str3 is assigned to str4. Both the variables refer to an instance of the System.String class 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.