Example (note the case):
string s = "Hello world!";
String s = "Hello world!";
What are the guidelines for the use of each? And what are the differences?
Example (note the case):
string s = "Hello world!";
String s = "Hello world!";
What are the guidelines for the use of each? And what are the differences?
string
andString
are identical in all ways (except the uppercase "S"). There are no performance implications either way.Lowercase
string
is preferred in most projects due to the syntax highlightingC# is a language which is used together with the CLR.
string
is a type in C#.System.String
is a type in the CLR.When you use C# together with the CLR
string
will be mapped toSystem.String
.Theoretically, you could implement a C#-compiler that generated Java bytecode. A sensible implementation of this compiler would probably map
string
tojava.lang.String
in order to interoperate with the Java runtime library.string
is just an alias forSystem.String
. The compiler will treat them identically.The only practical difference is the syntax highlighting as you mention, and that you have to write
using System
if you useString
.This YouTube video demonstrates practically how they differ.
But now for a long textual answer.
When we talk about
.NET
there are two different things one there is.NET
framework and the other there are languages (C#
,VB.NET
etc) which use that framework."
System.String
" a.k.a "String" ( capital "S") is a.NET
framework data type while "string" is aC#
data type.In short "String" is an alias ( the same thing called with different names) of "string". So technically both the below code statements will give the same output.
or
In the same way there are aliases for other c# data type as shown below:-
object:
System.Object
, string:System.String
, bool:System.Boolean
, byte:System.Byte
, sbyte:System.SByte
, short:System.Int16
and so onNow the million dollar question from programmer's point of view So when to use "String" and "string"?
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 declared using "string". At the right hand side we are calling a method so "String" is more sensible.
There's a quote on this issue from Daniel Solis' book.
I prefer the capitalized
.NET
types (rather than the aliases) for formatting reasons. The.NET
types are colored the same as other object types (the value types are proper objects, after all).Conditional and control keywords (like
if
,switch
, andreturn
) are lowercase and colored dark blue (by default). And I would rather not have the disagreement in use and format.Consider: