If you’re new to C#, you’ll notice there are sort of 2 types of strings – string and String. The first type is spelled out in lowercase letters; while the second is a proper noun.
Built-in Reference String Type
C# has a number of built-in reference types. One of them is the string type. It represents a sequence of zero or more Unicode characters and is an alias for System.String class in .NET.
Consider the following codes where we use string and String interchangeably. The codes compile and run successfully.
1 2 3 4 5 6 7 8 9 10 11 12 13 | static void Main(string[] args) { string name = "Karl"; String website = "www.turreta.com"; String temp_name = name; string temp_website = website; Console.WriteLine(temp_name); Console.WriteLine(temp_website); Console.ReadKey(); } |
In essence, string is a reserved word in C#.
Using With Collections
We can use both at the same time with collections. Here are some examples.
The following codes create a list of strings using both string and String.
1 2 3 4 5 6 7 | static void Main(string[] args) { List<String> persons = new List<string>(); persons.Add("Karl"); Console.WriteLine(persons.Count); Console.ReadKey(); } |
Take a look at the next code snippet. It uses both string types with Dictionary.
1 2 3 | Dictionary<String, string> config = new Dictionary<string, string>(); config.Add("app_name", "CLI App Demo"); config.Add("app_url", "htts://turreta.com/blog"); |
The codes will build and run successfully.
Key Differences
Although they are the same, there are key differences between them worth noting. The String requires to use using System; while string does not. Also, String is a type in the CLR; while string is a type in C#.
Generally, both are the same. We should choose one over the other when developing C# applications for consistency.