Quantcast
Channel: What is the difference between String and string in C#? - Stack Overflow
Viewing all articles
Browse latest Browse all 69

Answer by Shivprasad Koirala for What is the difference between String and string in C#?

$
0
0

This YouTube video demonstrates practically how they differ.

But now for a long textual answer.

When we talk about .NET there are two different things one there is .NET framework and the other there are languages (C#, VB.NET etc) which use that framework.

enter image description here

"System.String" a.k.a "String" (capital "S") is a .NET framework data type while "string" is a C# data type.

enter image description here

In short "String" is an alias (the same thing called with different names) of "string". So technically both the below code statements will give the same output.

String s = "I am String";

or

string s = "I am String";

In the same way, there are aliases for other C# data types as shown below:

object: System.Object, string: System.String, bool: System.Boolean, byte: System.Byte, sbyte: System.SByte, short: System.Int16 and so on.

Now the million-dollar question from programmer's point of view: So when to use "String" and "string"?

The first thing to avoid confusion use one of them consistently. But from best practices perspective when you do variable declaration it's good to use "string" (small "s") and when you are using it as a class name then "String" (capital "S") is preferred.

In the below code the left-hand side is a variable declaration and it is declared using "string". On the right-hand side, we are calling a method so "String" is more sensible.

string s = String.ToUpper() ;

Viewing all articles
Browse latest Browse all 69

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>