What is the difference between String and string in C#? Which one to use?


I recently came across a client’s code base which made use of “String” and “string” keywords. The Client wanted to clean up code and make them all consistent (string). With over 8 million lines of code and 50 plus developers working on 12 different features within the same SVN branch. This was going to be a mission.

From investigation we concluded that the task was massive and gains were trivial. This code cleanup was unnecessary and could be done little bit at a time.

Basically, in C# “string” is alias to “String” class which lives in the System namespace.

So, is there any difference?

No. Not at all. You can use either.

What built in type aliases are there?

Microsoft has the following built in Alias types.

C# Types              .NET type
bool                       System.Boolean
byte                       System.Byte
sbyte                      System.SByte
char                       System.Char
decimal                 System.Decimal
double                   System.Double
float                       System.Single
int                          System.Int32
uint                        System.UInt32
long                       System.Int64
ulong                     System.UInt64
object                    System.Object
short                      System.Int16
ushort                    System.UInt16
string                     System.String

Why have built in types?

The main reason is for readability. 



Its more intuitive to read code with blue keywords as seen above. Whereas the classes are more less for static method invocation.








As you can see from code above. The “String” is dimmer and has a suggestion.

When you inspect the suggestion in Visual Studio. You can see that suggestion is to simplify the name to lower case (string).

Summary.

  1. String or string does not matter.
  2. If you writing new code then better to follow Microsoft suggestions and go with built in aliases. Unless your company has a different standard.
  3. Don’t waste time in clean-ups.