The Difference Between string and String in C#

The Difference Between string and String in C#

This article explains the difference between string and String in C#.

Question

What’s the deal with the string and other types in C#? I see both string and String all over the place. Same goes with int and Int32 and other types.

For example, I see both:

string text = "Some Text Here";
String text = "Some More Text Here";

What is the difference between them?

Short Answer

None. There is no difference between them. Use the one you like best.

Really? No difference whatsoever? Why have both forms then? What’s the point?

Well…

Long Answer

There is a tiny difference between the two:

  • String is the name of the .NET class that represents a sequence of Unicode characters. Its full name is System.String.
  • string is the C# alias for the String class. It was created to make the string class look more friendly in C#. It is also a reserved keyword in C#.

Both forms are interchangeable in almost every place.

For example, this:

string name = "Red Pumpkin";
string sayonara = String.Format("Sayonara {0}!", name);

Can also be written as this:

String name = "Red Pumpkin";
String sayonara = string.Format("Sayonara {0}!", name);

Ok… So which is one better?

You decide!

Having said that, Microsoft’s examples have an overwhelming tendency to use the alias string when a type is mentioned and the class name String when some method or property is being requested from that class. This corresponds to the first example. In the interest of supporting helpful coding conventions, I personally go with that too.

You said almost every place… In what case are they different?

As stated, string is a reserved keyword. Yet String is not. It is just a class name. This means we can do weird stuff like so:

String String = "Some String";

While this will fail to compile:

String string = "Some String";
string string = "Some String";

So I have two ways of declaring a string… I’m not sure they’re enough. Can I have three?

You can have as many as you want. With the using keyword, you can create local aliases for any class you wish, including the base .NET Framework classes such as String.

using MyUnnecessaryAlias = System.String;

The question is… Why would you want to?

Jorge Candeias's Picture

About Jorge Candeias

Jorge helps organizations build high-performing solutions on the Microsoft tech stack.

London, United Kingdom https://jorgecandeias.github.io