Example (note the case):
string s = \"Hello world!\";
String s = \"Hello world!\";
What are
@JaredPar (a developer on the C# compiler and prolific SO user!) wrote a great blog post on this issue. I think it is worth sharing here. It is a nice perspective on our subject.
stringvs.Stringis not a style debate[...]
The keyword
stringhas concrete meaning in C#. It is the typeSystem.Stringwhich exists in the core runtime assembly. The runtime intrinsictly understands this type and provides the capabilities developers expect for strings in .NET. Its presence is so critical to C# that if that type doesn’t exist the compiler will exit before attempting to even parse a line of code. Hencestringhas a precise, unambiguous meaning in C# code.The identifier
Stringthough has no concrete meaning in C#. It is an identifier that goes through all the name lookup rules asWidget,Student, etc … It could bind to string or it could bind to a type in another assembly entirely whose purposes may be entirely different thanstring. Worse it could be defined in a way such that code likeString s = "hello"; continued to compile.class TricksterString { void Example() { String s = "Hello World"; // Okay but probably not what you expect. } } class String { public static implicit operator String(string s) => null; }The actual meaning of
Stringwill always depend on name resolution. That means it depends on all the source files in the project and all the types defined in all the referenced assemblies. In short it requires quite a bit of context to know what it means.True that in the vast majority of cases
Stringandstringwill bind to the same type. But usingStringstill means developers are leaving their program up to interpretation in places where there is only one correct answer. WhenStringdoes bind to the wrong type it can leave developers debugging for hours, filing bugs on the compiler team and generally wasting time that could’ve been saved by usingstring.Another way to visualize the difference is with this sample:
string s1 = 42; // Errors 100% of the time String s2 = 42; // Might error, might not, depends on the codeMany will argue that while this is information technically accurate using
Stringis still fine because it’s exceedingly rare that a code base would define a type of this name. Or that whenStringis defined it’s a sign of a bad code base.[...]
You’ll see that
Stringis defined for a number of completely valid purposes: reflection helpers, serialization libraries, lexers, protocols, etc … For any of these librariesStringvs.stringhas real consequences depending on where the code is used.So remember when you see the
Stringvs.stringdebate this is about semantics, not style. Choosing string gives crisp meaning to your code base. ChoosingStringisn’t wrong but it’s leaving the door open for surprises in the future.
Note: I copy/pasted most of the blog post for archive reason. I ignore some parts, so I recommend to skip and to read the blog post if you can.