Pages

Thursday 11 April 2013

Difference between "string" and "String" in C# and DOTNET

Difference between "string" and "String" in C# and DOTNET
 
Well, Difference between "string" and "String, is the obvious question anybody can ask you in any .NET technical interview. So be prepared for it.
 
"string" and "String" are same thing. "string" is a C# keyword which is simply an alias for the System.String. "string" is a compiler shortcut for System.String class.
 
"string" and "String" are interchangeable and there is no difference when and where you should use one or the other. But I will advise to be consistent with which one you did use though.
 
Difference between "string" and "String":
 
1. "string" does not exist in .NET, it only exists in C#. .NET Framework implicitly converts "string" into "System.String" which is compatible with .NET Framework. CTS (Common Type System) does this conversion. String belongs to .NET platform (is accessible in all languages), while string is language specific (C#). Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference.
 
2. "String" is an class (System.String) and is a Reference type while "string" is value type.
 
3. String is a class name while string is a restricted keyword
 
When to use what?
 
You can use whichever you prefer, although I generally use string when I'm planning on using it much like a primitive data type (similar to int, float, or bool) and String when I'm planning on using it as an object/class. For example:
 
string abc = "   ";
if (String.isNullOrWhitespace(abc))
{
    // ...
}
 
In the case above, I'm planning on using abc simply to store some text (effectively as a primitive), so I use string; however, when I call String.isNullOrWhitespace(string), I use String. I do this, because generally the first letter of class names are capitalized (String) while the first letter of primitives (such as int) are not.

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.