String vs string in C# code

What is the difference between String and string in C# code?

I reviewed one of our team members code and realized that he changed some existing code from string to String.
Honestly, I haven’t really thought about this. I knew it performs same.

string is alias of System.String object.

string is type in C#
System.String is a type in the CLR
When you use C# together with the CLR string will be mapped to System.String
 So technically both the below code statements will give the same output.

String s = "This is a String";

or

string s = "This is a String"

The first thing to avoid confusion use one of them consistently. But from best practices perspective when you do variable declaration it’s good to use “string” (small “s”) and when you are using it as a class name then “String” (capital “S”) is preferred.

In the below code the left-hand side is a variable declaration and it is declared using “string”. On the right-hand side, we are calling a method so “String” is more sensible.

string s = String.ToUpper();

Leave a Reply