Difference between string and String tutorials | C# Examples

this tutorial talks about the difference between string and String in C#.

In C# Language, Every type has a compiled to a type in .Net Framework, So String is equivalent to the type System.String class.

string is an alias for a System.String class in C#.

Both are used to declare a variable of a string and can be used interchangeably.

string name = "Mark";
String name = "Eric";

Let’s see the difference between a string and a String

Difference between string and String in C#

  • string is a keyword, and String is a class name. string keyword can not be used as a variable.
using System;

public class Program
{
    public static void Main()
    {
        const int String = 12; // Compiles fine
        const int string = 11; // Compilation error

    }
}
  • String must be used by referencing using the System directive. system works without the System directive

If there is no using System directive, it throws Compilation error (line 6, col 3): The type or namespace name ‘String’ could not be found (are you missing a using directive or an assembly reference?)

The below program declares a variable of String, but there is no System reference in the first line

public class Program
{
    public static void Main()
    {
        String str = "123"; // Compilation error

    }
}

using string without the System directive works fine due to the global alias for System.String

public class Program
{
    public static void Main()
    {
        string str = "123"; // Compiles ok

    }
}
  • string is a datatype, Syntax highlighted in color in Visual Studio code. But String not highlighted in color.

  • In Coding guidelines and styles, string is a preferrable case for data types. System is a pascal case

  • string can be used for the declaration of fields, properties whereas String is used for methods such as String.Lowercase()