It can be a little confusing if you are very new to the language. Why do we have a keyword in lower case and the same keyword with a capital S? What’s the difference?

In short, there isn’t really one. Both keywords relate to the String class provided within the System namespace. However, there is a distinction between the two keywords in terms of their implementation.

The lower case ‘string’ keyword is an alias, which points to the String class in System.String. That’s it really.

So why use an alias?

If I had to guess, I’d say the main reason for having an alias is the high usage of String objects in programming. Using the lower case string alias, you can refer to a String object without importing the System namepsace.

So is it just for convenience?

Well, partly. However, it is widely accepted that the best practice in C# is the following:

  • If you’re creating a string variable / just need a string object to use or refer to in your code, use string.
string myString = "bar";
  • If you need to refer to the actual String class (String.Format for example), use String
string finalString = String.Format("foo {0}", myString);
        

author image

About NIck

3 Comments

  1. One notable affect: If your code does include a “using System;” then saying

    String myString = “bar”;

    will fail, while

    string myString = “bar”;

    will succeed.

  2. Ooops… Typo in the above. ” If your code DOESN’T include “

    1. Nice! Good point and a good thing to bear in mind. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

You Might Also Like...

anxious young lady with tickets and passport on red background