Back to Basics – string Vs. String in C#

Back to Basics – string Vs. String in C#

One of the frequent question that comes during the .NET interview is “What is the difference between string and String?” . This one is a very simple question but can make you confused during the interview. So, let’s try to recall and check what exactly they are. To answer this question in a short, The two are indeed synonymous. String stands for System.String and  string is an alias for String. There is no actually any different, both of them compiled into same code (IL Code – System.String) and they are same during execution time.

Consider you have following code

class Program
{
static void Main(string[] args)
{
string url = "<a href="https://dailydotnettips.com&quot;;">https://dailydotnettips.com";</a>
String tags = ".net, tips, C#";
}
}

Must Read :  Using or Using ?

Now, if you point over either of string or String, you will have same message as tooltip, as they are referring to the same.

image

While there representation is different, they are referring to same type when in comes under the Intermediate Language (IL). You can view the same by using IL DASM Tool.

image

You must have to include a using System when using String, otherwise you get the following error:

The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?)

When we talked about Common Language Runtime, and IL, you can explore this topic with respect to other code language such as Visual Basic as well.

Module Module1
Sub Main()
Dim mystring As String = "This is VB Code Base"
End Sub

End Module

image

Here we also defined a variable using String ( As we do in VB), but when it comes into IL it is same representation it is same for language.

string and String are not alone, there are similar aliases for other c# data type and few of them given in below.
object: System.Object
bool: System.Boolean
byte: System.Byte
int: System.Int32

As a common  practices perspective when we use string for declaration of variable, and when you are using it as a class name then “String“. ( For an example String.Format, String.Compare etc.)

Hope this will clears your doubts.

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

6 Comments to “Back to Basics – string Vs. String in C#”

Comments are closed.