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";">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.
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.
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
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.
Nice article
Pingback: Dew Drop – May 12, 2015 (#2012) | Morning Dew
This is something that many are confused with. Thank you for this article.
Thanks mate !
Pingback: Visual Studio Extensions Future - The Daily Six Pack
Pingback: .NET Tips and Tricks from Daily .NET Tips : May 2015 Links | Abhijit's World of .NET