Are you confused about System.String and string in C#? What is the difference between String and string in C#? And how to choose between string and System.String? In this article, I am going to show you all the differences between string and System.String in C# with code examples.
What is the difference between System.String and string in C#?
Basically, there is no difference between string and String in C#. "string" is just an alias of System.String and both are compiled in the same manner. String stands for System.String, and it is a .NET Framework type. "string" is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference.
string s="Hello ";
String st="World";
So, the question is if both strings do the same job, then why do we need to invent another one for the confused programmer? The answer is very simple. "string" is just a keyword which provides limited functionality and is mainly used in creating a variable. Whereas, System.String is a class which gives you a rich set of functions and properties to manipulate the string.
Known differences between string and System.String in C#?
- string is a keyword and widely used for declaring a variable. Whereas System.String is a class and used for accessing string static methods like String.Format(), String.Compare() etc.
- You can use string directly in your program and you don’t need to add Using System namespace at the beginning of your program whereas to using System.String you need to import Using System namespace.
- As a long map to System.Int64, int maps to System.Int32 and short map to System.Int16; string map to System.String.
Code Example: String vs string in C#
using System;
namespace ConsoleApplication {
public class Program {
public static void Main(string[] args) {
string s = "Hello ";
string t = "World";
string st = String.Concat(s, t);
Console.WriteLine(st);
}
}
}
Here, you can see that string is used for declaring variable whereas String is used for accessing the static method String.Concat() that joins two strings together.
Hopefully, this clears up any issues!