Wednesday, August 12, 2015

C# : String vs. string

I have seen this confusion over and over, and thought of writing a post about it. Basically String and string are both the same. If you go to definition (F12) on String or string, you will see that you will be navigated to the same String class. string is an alias for System.String.

So now you must be thinking, if these two are similar, when should we use String or string. Again there is no strict rule for which to use, but as a practice we are maintaining following standards. If you are using the string type for a variable, use string. If you accessing String classes' methods, then use String.

Let me show you what I mean.
class Program
    static void Main(string[] args)
        string value1 = System.String.Empty;
        string value2 = System.String.Format("{0} {1}", "Hello", "World");
        string value3 = System.String.Concat("Hello", " ", "World");
        if (System.String.IsNullOrEmpty(value1))
            // some implementation
        // etc.
class String

Above code will be compiling fine. But it’s good to note one important thing. string is a reserved keyword and String is yet another class. So theoretically there is nothing wrong having an another class named String in your project. But that is highly unlikely.

Hope this helps.

Happy Coding.


No comments:

Post a Comment