What is the difference between System.String and string?

One of the questions that lot of developers ask is – Is there any difference between string and System.String and what should be used?

 

Short Answer

There is no difference between the two.  You can use either of them in your code.

 

Explanation

 

System.String is a class (reference type) defined the mscorlib in the namespace System.  In other words, System.String is a type in the CLR.

string is a keyword in C#

 

Before we understand the difference, let us understand BCL and FCL terms.

BCL is Common Language Infrastructure (CLI) available to languages like C#, A#, Boo, Cobra, F#, IronRuby, IronPython and other CLI languages.  It includes common functions such as File Read/Write or IO and database/XML interactions.  BCL was first implemented in Microsoft .NET in the form of mscorlib.dll

FCL is standard Microsoft .NET specific library containing reusable classes/assets like System, System.CodeDom, System.Collections, System.Diagnostics, System.Globalization, System.IO, System.Resources and System.Text

Now in C#, string (keyword in BCL) directly maps to System.String (an FCL type).  Similarly, int maps directly to System.Int32. 

Here int is mapped to a integer type that is 32 bit.  But in other language, you could probably map int (keyword in BCL) to a 64 bit integer (FCL type).

So the fact that using string and System.String in C# makes no difference is well established.

 

Is it better to still use string instead of System.String?

 

There is no universally agreed answer to this.

But, as per me, even though both string and System.String mean the same and have no difference in performance of the application, it is better to use string.  This is because string is a C# language specific keyword.

Also C# language specification states,

As a matter of style, use of the keyword is favored over use of the complete system type name

Following this practice ensures that your code consistently uses keywords wherever possible rather than having a code with BCL and FCL types used.

Related Posts:

2 thoughts on “What is the difference between System.String and string?

  1. While there is not difference, there is a fundamental difference in how they should be consumed.

    string itself is a very specialised case since its immutable reference type yet it is exposed as a primitive datatype.

    In dotnet the common fashion is to use primitive types when declaring instances and to use Class types when accessing static methods.
    string firstname = “Hermit”;
    string surname = “Dave”;
    string fullName = String.Format(“{0} {1}”, firstname, surname);

    While you can use string.Format instead of String.Format that is not the preferred approach across .NET

Leave a Reply

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


*

Current day month ye@r *