If you come from another programming background (e.g Java), you may noticed that in C# you're able to use string and String to declare a string variable in your code.
String textA = "Hello";
string textB = "Hello";
And you may asked to yourself, both works anyway but, there's any difference between them? technically no.
string is an alias in C# for System.String. It can be compared in a case like int and System.Int32, just an integer or just like the bool and Boolean. Both of them are compiled to System.String in IL (Intermediate Language)
string is a reserved word and String is a class name. This means that string cannot be used as a variable name by itself i.e :
StringBuilder String = new StringBuilder(); // Compile succesfully
StringBuilder string = new StringBuilder(); // Doesn't compile
Therefore comes in handy to use string, the code using string will never break, but there is a slim chance that code using String will. (You can redefine String, but not string).
If you need to refer specifically to the class, is recommendable to use String i.e :
Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0:C2} per ounce.", pricePerOunce);
string is just one of all the aliases that C# has built in, unlike Java. You can see all the aliases in the following list:
object: System.Object
string: System.String
bool: System.Boolean
byte: System.Byte
sbyte: System.SByte
short: System.Int16
ushort: System.UInt16
int: System.Int32
uint: System.UInt32
long: System.Int64
ulong: System.UInt64
float: System.Single
double: System.Double
decimal: System.Decimal
char: System.Char
As said before, you can use the aliases without even import use System;
Final conclusion
string is a keyword, and you can't use string as an identifier.
String is not a keyword, and you can use it as an identifier:
string String = "I am a string";
The keyword string is an alias for System.String aside from the keyword issue, the two are exactly equivalent, therefore :
typeof(string) == typeof(String) == typeof(System.String)
Notes
- You can use
stringwithout import any component, opposite toStringas you can't useStringwithoutusing System;beforehand. - You can't use string in reflection; you must use
String. - To avoid confusion use one of them consistently. But from best practices perspective when you do variable declaration it's good to use
stringand when you are using it as a class name thenStringis preferred.