Difference between string and String in C#
Essentially, there is no difference between string and String (capital S) in C#.
String (capital S) is a class in the .NET framework in the System namespace. The fully qualified name is System.String. Whereas, the lower case string is an alias of System.String.
Consider the following example.
string str1= "Hello";
String str2 = "World!";
Console.WriteLine(str1.GetType().FullName); // System.String
Console.WriteLine(str2.GetType().FullName); // System.String
As you can see in the above example, the full name of both types are System.String. So, this proves that both are same.
Write string and String in .cs file in Visual Studio and put the cursor on it and press F12. Both will take you to the sealed class String.
It is recommended to use string (lower case) over String. However, it's a matter of choice. You can use any of them. Many developers use string to declare variables in C# and use System.String class to use any built-in string methods e.g., String.IsNullOrEmpty().
Please note that you must import System namespace at the top of your .cs file to use String class, whereas string keyword can be used directly without any namespace.
.NET includes different aliases for different types. The following table lists data type aliases.
Alias | .NET Type | Type |
---|---|---|
byte | System.Byte | struct |
sbyte | System.SByte | struct |
int | System.Int32 | struct |
uint | System.UInt32 | struct |
short | System.Int16 | struct |
ushort | System.UInt16 | struct |
long | System.Int64 | struct |
ulong | System.UInt64 | struct |
float | System.Single | struct |
double | System.Double | struct |
char | System.Char | struct |
bool | System.Boolean | struct |
object | System.Object | Class |
string | System.String | Class |
decimal | System.Decimal | struct |
DateTime | System.DateTime | struct |