Lance Fisher
Lance Fisher

Reputation: 25813

What is the difference between String and string in C#?

What are the differences between these two, and which one should I use?

string s = "Hello world!";
String s = "Hello world!";

Upvotes: 7577

Views: 1338961

Answers (30)

Jon Skeet
Jon Skeet

Reputation: 1502985

Just for the sake of completeness, here's a brain dump of related information...

As others have noted, string is an alias for System.String. Assuming your code using String compiles to System.String (i.e. you haven't got a using directive for some other namespace with a different String type), they compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

bool:    System.Boolean
byte:    System.Byte
char:    System.Char
decimal: System.Decimal
double:  System.Double
float:   System.Single
int:     System.Int32
long:    System.Int64
nint:    System.IntPtr
object:  System.Object
sbyte:   System.SByte
short:   System.Int16
string:  System.String
uint:    System.UInt32
ulong:   System.UInt64
ushort:  System.UInt16

Apart from string and object, the aliases are all to value types. decimal is a value type, but not a primitive type in the CLR.

In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime literals, and has an alias for it too.)

There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the integral-type production, which is one token of sbyte, byte, short, ushort, int, uint, long, ulong, char... as opposed to a type production as used by variable declarations for example. It doesn't indicate any other difference.

Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language-neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language that defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.

Upvotes: 3826

Nima Habibollahi
Nima Habibollahi

Reputation: 480

Technically there is no difference, but there are these minor differences:

  • Language vs framework: string is alias built in data-type and alias keywords but String is alias part of class library: System.string. string doesn`t need to import even the namespace (using System;)
  • Syntax highlighting: In some editors, the keywords are highlighted with different color
  • Clean code: Its is recommended to Start types by capital letters.

Upvotes: -3

user3296
user3296

Reputation: 389

There is one difference - you can't use String without using System; beforehand.

Updated:

"String" with a capital "S" is a keyword that refers to the built-in string data type in the .NET Framework's Base Class Library. It is a reference type that represents a sequence of characters.

On the other hand, "string" with a lowercase "s" is an alias for the "System.String" type, which means they are essentially the same thing. The use of "string" is just a shorthand way of referring to the "System.String" type, and it is used more commonly in C# code.

Both "String" and "string" are interchangeable in C#, and you can use either one to declare a variable of type string.

String myString = "Hello World"; // using the String keyword
string myString = "Hello World"; // using the string alias

However, it is recommended to use the "string" alias in C# code for consistency with the rest of the language's syntax and convention.

Here you can read more about C# String

Upvotes: 479

Abrar ul Hassan
Abrar ul Hassan

Reputation: 1

The tiny difference between string and String in C#. the string is just an alias of the system. String. Both string and Strings are compiled in the same manner. Answer is very Simple. string is keyword provide limited functionality and mainly use string creating variable like (string name = "Abrar"). Or we can say it is a datatype we use especial for alphabetic. and String is a class which give rich set of functions and properties manipulate the string. Hopefully You Will understand easily.

Upvotes: -3

DanConsultant
DanConsultant

Reputation: 53

A good way to thing about it is string is a data type where String is a class type. Each have different methods and which one to use depends on your need.

Upvotes: -9

Derek Park
Derek Park

Reputation: 46856

string is an alias in C# for System.String.
So technically, there is no difference. It's like int vs. System.Int32.

As far as guidelines, it's generally recommended to use string any time you're referring to an object.

e.g.

string place = "world";

Likewise, I think it's generally recommended to use String if you need to refer specifically to the class.

e.g.

string greet = String.Format("Hello {0}!", place);

This is the style that Microsoft tends to use in their examples.

It appears that the guidance in this area may have changed, as StyleCop now enforces the use of the C# specific aliases.

Upvotes: 7107

Nima Habibollahi
Nima Habibollahi

Reputation: 480

There are at least 4 differences:

1- string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.

2- you can't use String without "using System".so you write less code by using "string".

3- 'String' is better naming convention than 'string', as it is a type not variable.

4- "string" is a C# keyword and syntax highlighted in most coding editors, but not "String".

Upvotes: -5

Ran Turner
Ran Turner

Reputation: 18116

Essentially, there is no difference between string and String in C#.

String is a class in the .NET framework in the System namespace under System.String, Whereas, lower case string is an alias of System.String.

Logging the full name of both types can prove this

string s1= "hello there 1";
String s2 = "hello there 2";
        
Console.WriteLine(s1.GetType().FullName); // System.String
Console.WriteLine(s2.GetType().FullName); // System.String

It is recommended to use string over String but it's really a matter of choice. Most developers use string to declare variables in C# and use System.String class to use any built-in string methods like for an example , the String.IsNullOrEmpty() method.

Upvotes: 5

Saurabh
Saurabh

Reputation: 1631

string is equal to System.String in VS2015 if you write this:

System.String str;

Than compiler will show potential fix to optimize it and after applying that fixe it will look like this

string str;

Upvotes: 12

hubot
hubot

Reputation: 391

To be honest, in practice usually there is not difference between System.String and string.

All types in C# are objects and all derives from System.Object class. One difference is that string is a C# keyword and String you can use as variable name. System.String is conventional .NET name of this type and string is convenient C# name. Here is simple program which presents difference between System.String and string.

string a = new string(new char[] { 'x', 'y', 'z' });
string b = new String(new char[] { 'x', 'y', 'z' });
String c = new string(new char[] { 'x', 'y', 'z' });
String d = new String(new char[] { 'x', 'y', 'z' });
MessageBox.Show((a.GetType() == typeof(String) && a.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((b.GetType() == typeof(String) && b.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((c.GetType() == typeof(String) && c.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((d.GetType() == typeof(String) && d.GetType() == typeof(string)).ToString()); // shows true

@JonSkeet in my compiler

public enum Foo : UInt32 { }

is working. I've Visual Studio 2015 Community.

Upvotes: 13

wild coder
wild coder

Reputation: 900

First of All, both string & String are not same. There is a difference: String is not a keyword and it can be used as an identifier whereas string is a keyword and cannot be used as identifier.

I am trying to explain with different example : First, when I put string s; into Visual Studio and hover over it I get (without the colour):
String Definition

That says that string is System.String, right? The documentation is at https://msdn.microsoft.com/en-us/library/362314fe.aspx. The second sentence says "string is an alias for String in the .NET Framework.".

Upvotes: 14

Shivprasad Koirala
Shivprasad Koirala

Reputation: 28666

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() ;

Upvotes: 227

Taslim Oseni
Taslim Oseni

Reputation: 6273

In C#, string is the shorthand version of System.String (String). They basically mean the same thing.

It's just like bool and Boolean, not much difference..

Upvotes: 15

TRK
TRK

Reputation: 198

There is no major difference between string and String in C#.

String is a class in the .NET framework in the System namespace. The fully qualified name is System.String. The lower case string is an alias of System.String.

But its recommended to use string while declaring variables like:

string str = "Hello";

And we can use String while using any built-in method for strings like String.IsNullOrEmpty().

Also one difference between these two is like before using String we have to import system namespace in cs file and string can be used directly.

Upvotes: 5

aloisdg
aloisdg

Reputation: 23531

@JaredPar (a developer on the C# compiler and prolific SO user!) wrote a great blog post on this issue. I think it is worth sharing here. It is a nice perspective on our subject.

string vs. String is not a style debate

[...]

The keyword string has concrete meaning in C#. It is the type System.String which exists in the core runtime assembly. The runtime intrinsically understands this type and provides the capabilities developers expect for strings in .NET. Its presence is so critical to C# that if that type doesn’t exist the compiler will exit before attempting to even parse a line of code. Hence string has a precise, unambiguous meaning in C# code.

The identifier String though has no concrete meaning in C#. It is an identifier that goes through all the name lookup rules as Widget, Student, etc … It could bind to string or it could bind to a type in another assembly entirely whose purposes may be entirely different than string. Worse it could be defined in a way such that code like String s = "hello"; continued to compile.

class TricksterString { 
  void Example() {
    String s = "Hello World"; // Okay but probably not what you expect.
  }
}

class String {
  public static implicit operator String(string s) => null;
}

The actual meaning of String will always depend on name resolution. That means it depends on all the source files in the project and all the types defined in all the referenced assemblies. In short it requires quite a bit of context to know what it means.

True that in the vast majority of cases String and string will bind to the same type. But using String still means developers are leaving their program up to interpretation in places where there is only one correct answer. When String does bind to the wrong type it can leave developers debugging for hours, filing bugs on the compiler team, and generally wasting time that could’ve been saved by using string.

Another way to visualize the difference is with this sample:

string s1 = 42; // Errors 100% of the time  
String s2 = 42; // Might error, might not, depends on the code

Many will argue that while this is information technically accurate using String is still fine because it’s exceedingly rare that a codebase would define a type of this name. Or that when String is defined it’s a sign of a bad codebase.

[...]

You’ll see that String is defined for a number of completely valid purposes: reflection helpers, serialization libraries, lexers, protocols, etc … For any of these libraries String vs. string has real consequences depending on where the code is used.

So remember when you see the String vs. string debate this is about semantics, not style. Choosing string gives crisp meaning to your codebase. Choosing String isn’t wrong but it’s leaving the door open for surprises in the future.

Note: I copy/pasted most of the blog posts for archive reasons. I ignore some parts, so I recommend skipping and reading the blog post if you can.

Upvotes: 82

MicroservicesOnDDD
MicroservicesOnDDD

Reputation: 363

There are many (e.g. Jeffrey Richter in his book CLR Via C#) who are saying that there is no difference between System.String and string, and also System.Int32 and int, but we must discriminate a little deeper to really squeeze the juice out of this question so we can get all the nutritional value out of it (write better code).

A. They are the Same...

  1. to the compiler.
  2. to the developer. (We know #1 and eventually achieve autopilot.)

B. They are Different in Famework and in Non-C# Contexts. Different...

  1. to OTHER languages that are NOT C#
  2. in an optimized CIL (was MSIL) context (the .NET VM assembly language)
  3. in a platform-targeted context -- the .NET Framework or Mono or any CIL-type area
  4. in a book targeting multiple .NET Languages (such as VB.NET, F#, etc.)

So, the true answer is that it is only because C# has to co-own the .NET space with other languages that this question even exists.

C. To Summarize...

You use string and int and the other C# types in a C#-only targeted audience (ask the question, who is going to read this code, or use this library). For your internal company, if you only use C#, then stick to the C# types.

...and you use System.String and System.Int32 in a multilingual or framework targeted audience (when C# is not the only audience). For your internal organization, if you also use VB.NET or F# or any other .NET language, or develop libraries for consumption by customers who may, then you should use the "Frameworky" types in those contexts so that everyone can understand your interface, no matter what universe they are from. (What is Klingon for System.String, anyway?)

HTH.

Upvotes: 5

Ali Sufyan
Ali Sufyan

Reputation: 94

Image result for string vs String www.javatpoint.com In C#, string is an alias for the String class in .NET framework. In fact, every C# type has an equivalent in .NET.
Another little difference is that if you use the String class, you need to import the System namespace, whereas you don't have to import namespace when using the string keyword

Upvotes: 2

Ted Mucuzany
Ted Mucuzany

Reputation: 33

All the above is basically correct. One can check it. Just write a short method

public static void Main()
{
    var s = "a string";
}

compile it and open .exe with ildasm to see

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] string s)
  IL_0000:  nop
  IL_0001:  ldstr      "a string"
  IL_0006:  stloc.0
  IL_0007:  ret
} // end of method Program::Main

then change var to string and String, compile, open with ildasm and see IL does not change. It also shows the creators of the language prefer just string when difining variables (spoiler: when calling members they prefer String).

Upvotes: 5

Gonçalo Garrido
Gonçalo Garrido

Reputation: 118

declare a string variable with string but use the String class when accessing one of its static members:

String.Format()

Variable

string name = "";

Upvotes: 4

claudioalpereira
claudioalpereira

Reputation: 61

I'd just like to add this to lfousts answer, from Ritchers book:

The C# language specification states, “As a matter of style, use of the keyword is favored over use of the complete system type name.” I disagree with the language specification; I prefer to use the FCL type names and completely avoid the primitive type names. In fact, I wish that compilers didn’t even offer the primitive type names and forced developers to use the FCL type names instead. Here are my reasons:

  • I’ve seen a number of developers confused, not knowing whether to use string or String in their code. Because in C# string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used. Similarly, I’ve heard some developers say that int represents a 32-bit integer when the application is running on a 32-bit OS and that it represents a 64-bit integer when the application is running on a 64-bit OS. This statement is absolutely false: in C#, an int always maps to System.Int32, and therefore it represents a 32-bit integer regardless of the OS the code is running on. If programmers would use Int32 in their code, then this potential confusion is also eliminated.

  • In C#, long maps to System.Int64, but in a different programming language, long could map to an Int16 or Int32. In fact, C++/CLI does treat long as an Int32. Someone reading source code in one language could easily misinterpret the code’s intention if he or she were used to programming in a different programming language. In fact, most languages won’t even treat long as a keyword and won’t compile code that uses it.

  • The FCL has many methods that have type names as part of their method names. For example, the BinaryReader type offers methods such as ReadBoolean, ReadInt32, ReadSingle, and so on, and the System.Convert type offers methods such as ToBoolean, ToInt32, ToSingle, and so on. Although it’s legal to write the following code, the line with float feels very unnatural to me, and it’s not obvious that the line is correct:

    BinaryReader br = new BinaryReader(...);
    float val = br.ReadSingle(); // OK, but feels unnatural
    Single val = br.ReadSingle(); // OK and feels good
    
  • Many programmers that use C# exclusively tend to forget that other programming languages can be used against the CLR, and because of this, C#-isms creep into the class library code. For example, Microsoft’s FCL is almost exclusively written in C# and developers on the FCL team have now introduced methods into the library such as Array’s GetLongLength, which returns an Int64 value that is a long in C# but not in other languages (like C++/CLI). Another example is System.Linq.Enumerable’s LongCount method.

I didn't get his opinion before I read the complete paragraph.

Upvotes: 93

Braham Prakash Yadav
Braham Prakash Yadav

Reputation: 22

it is common practice to declare a variable using C# keywords. In fact, every C# type has an equivalent in .NET. As another example, short and int in C# map to Int16 and Int32 in .NET. So, technically there is no difference between string and String, but In C#, string is an alias for the String class in .NET framework.

Upvotes: 6

user9131762
user9131762

Reputation:

String is the class of string. If you remove System namespace from using statements, you can see that String has gone but string is still here. string is keyword for String. Like
int and Int32
short and Int16
long and Int64

So the keywords are just some words that uses a class. These keywords are specified by C#(so Microsoft, because C# is Microsoft's). Briefly, there's no difference. Using string or String. That doesn't matter. They are same.

Upvotes: 5

Mel
Mel

Reputation: 2385

It's a matter of convention, really. string just looks more like C/C++ style. The general convention is to use whatever shortcuts your chosen language has provided (int/Int for Int32). This goes for "object" and decimal as well.

Theoretically this could help to port code into some future 64-bit standard in which "int" might mean Int64, but that's not the point, and I would expect any upgrade wizard to change any int references to Int32 anyway just to be safe.

Upvotes: 80

user8207463
user8207463

Reputation:

string is a shortcut for System.String. The only difference is that you don´t need to reference to System.String namespace. So would be better using string than String.

Upvotes: 7

Jaider
Jaider

Reputation: 14944

As you already know string is just alias for System.String. But what should I use? it just personal preference.

In my case, I love to use string rather than use System.String because String requires a namespace using System; or a full name System.String.

So I believe the alias string was created for simplicity and I love it!

Upvotes: 7

Luke Foust
Luke Foust

Reputation: 2234

The best answer I have ever heard about using the provided type aliases in C# comes from Jeffrey Richter in his book CLR Via C#. Here are his 3 reasons:

  • I've seen a number of developers confused, not knowing whether to use string or String in their code. Because in C# the string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used.
  • In C#, long maps to System.Int64, but in a different programming language, long could map to an Int16 or Int32. In fact, C++/CLI does in fact treat long as an Int32. Someone reading source code in one language could easily misinterpret the code's intention if he or she were used to programming in a different programming language. In fact, most languages won't even treat long as a keyword and won't compile code that uses it.
  • The FCL has many methods that have type names as part of their method names. For example, the BinaryReader type offers methods such as ReadBoolean, ReadInt32, ReadSingle, and so on, and the System.Convert type offers methods such as ToBoolean, ToInt32, ToSingle, and so on. Although it's legal to write the following code, the line with float feels very unnatural to me, and it's not obvious that the line is correct:
BinaryReader br = new BinaryReader(...);
float val  = br.ReadSingle(); // OK, but feels unnatural
Single val = br.ReadSingle(); // OK and feels good

So there you have it. I think these are all really good points. I however, don't find myself using Jeffrey's advice in my own code. Maybe I am too stuck in my C# world but I end up trying to make my code look like the framework code.

Upvotes: 597

Hasan Jafarov
Hasan Jafarov

Reputation: 628

string is short name of System.String. String or System.String is name of string in CTS(Common Type System).

Upvotes: 8

zap92
zap92

Reputation: 269

There is practically no difference

The C# keyword string maps to the .NET type System.String - it is an alias that keeps to the naming conventions of the language.

Upvotes: 23

Pritam Jyoti Ray
Pritam Jyoti Ray

Reputation: 330

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

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#

Upvotes: 9

Ronnie
Ronnie

Reputation: 8117

System.String is the .NET string class - in C# string is an alias for System.String - so in use they are the same.

As for guidelines I wouldn't get too bogged down and just use whichever you feel like - there are more important things in life and the code is going to be the same anyway.

If you find yourselves building systems where it is necessary to specify the size of the integers you are using and so tend to use Int16, Int32, UInt16, UInt32 etc. then it might look more natural to use String - and when moving around between different .net languages it might make things more understandable - otherwise I would use string and int.

Upvotes: 317

Related Questions