What is the difference between String and string in C#?

Here, we are going to learn what is the difference between String and string in C#.Net?
Submitted by IncludeHelp, on January 13, 2021

There is no difference between String and string, both are the same technically. string is an alias of System.String class. Like other class and their aliases: int can be used for System.Int32 class.

Consider the below example,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "Welcome at IncludeHelp";
            String str2 = "Welcome at IncludeHelp";

            //printing the values
            Console.WriteLine("Values...");
            Console.WriteLine("str1 = " + str1);
            Console.WriteLine("str2 = " + str2);

            //printing the types
            Console.WriteLine("Types...");
            Console.WriteLine("Type of str1 = " + str1.GetType().FullName);
            Console.WriteLine("Type of str2 = " + str2.GetType().FullName);

            Console.Read();
        }
    }
}

Output:

Values...
str1 = Welcome at IncludeHelp
str2 = Welcome at IncludeHelp
Types...
Type of str1 = System.String
Type of str2 = System.String

Guidelines for the use of String and string

It's generally recommended that,

  • string should be used to declare variables i.e., for referring objects.
    string str = "Welcome at IncludeHelp";
    
  • String should be used to refer a class.
    string str = String.Format("{0}", "Welcome at IncludeHelp");
    

Consider the below example,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "Welcome at IncludeHelp";
            String str2 = String.Format("{0}", "Welcome at IncludeHelp");

            //printing the values
            Console.WriteLine("Values...");
            Console.WriteLine("str1 = " + str1);
            Console.WriteLine("str2 = " + str2);

            //printing the types
            Console.WriteLine("Types...");
            Console.WriteLine("Type of str1 = " + str1.GetType().FullName);
            Console.WriteLine("Type of str2 = " + str2.GetType().FullName);

            Console.Read();
        }
    }
}

Output:

Values...
str1 = Welcome at IncludeHelp
str2 = Welcome at IncludeHelp
Types...
Type of str1 = System.String
Type of str2 = System.String



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.