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?
System.String
is the .NET string class - in C#string
is an alias forSystem.String
- so in use they are the same.As for guidelines I wouldn't get too bogged down and just use whichever you feel like - there are more important things in life and the code is going to be the same anyway.
If you find yourselves building systems where it is necessary to specify the size of the integers you are using and so tend to use
Int16
,Int32
,UInt16
,UInt32
etc. then it might look more natural to useString
- and when moving around between different .net languages it might make things more understandable - otherwise I would use string and int.There is one difference - you can't use
String
withoutusing System;
beforehand.Against what seems to be common practice among other programmers, I prefer
String
overstring
, just to highlight the fact thatString
is a reference type, as Jon Skeet mentioned.There is no difference between the two -
string
, however, appears to be the preferred option when considering other developers' source code.Using System types makes it easier to port between C# and VB.Net, if you are into that sort of thing.
The best answer I have ever heard about using the provided type aliases in C# comes from Jeffrey Richter in his book CLR Via C#. Here are his 3 reasons:
So there you have it. I think these are all really good points. I however, don't find myself using Jeffrey's advice in my own code. Maybe I am too stuck in my C# world but I end up trying to make my code look like the framework code.