string vs. String in C#

In the last time I have had heard one question several times: “What is the difference between ‘string’ and ‘String’”? Furthermore during several code reviews I have seen a mix-up of these two notations. Therefore, within this article I want to explain the differences between these two notations.

string or String

The two different string notations are equal but not the same. “String” stands for the .NET Framework type System.String. “string” instead is a keyword in the C# language. It is an alias for the System.String. Therefore “String” and “string” compile to the same code. So at execution time there is no deference between them. The following source code is used to get the type of both objects.

Console.WriteLine("string = " + typeof(string));
Console.WriteLine("String = " + typeof(String));

The console application creates the following output:
string = System.String
String = System.String

Coding conventions

During execution time there is no difference between “string” and “String”. But during implementation time they are not the same. Therefore you should respect the existing code conventions when to use which notation. There are two basic rules:

  • Use “string” to create an object instance
  • Use “String” to access the (static) methods of the object

The following example shows a good and a bad example. At first the right notations according to the coding guidelines are used and as second the wrong notation is used. Both examples will work fine. But if you follow the coding conventions you will increase readability of your source code.

//good example
string myValue = null;
myValue = String.Concat("Hello", " ", "World");

//bad example (will also work but violates coding conventions)
String myOtherValue = null;
myOtherValue = string.Concat("Hello", " ", "World");


“string” and “String” are equal bot not the same. At execution time there is no difference between both notations but at implementation time you should follow some coding conventions to increase the readability of you source code.

Dieser Beitrag wurde unter .NET, C# abgelegt und mit verschlagwortet. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

Du kommentierst mit deinem Abmelden /  Ändern )


Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s