By Lance Fisher


2008-08-10 07:18:02 8 Comments

Example (note the case):

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

What are the guidelines for the use of each? And what are the differences?

30 comments

@faryal rida 2019-09-23 09:22:23

Well technically both of these are the same but with a slight difference. While “string” is a datatype, whereas “String” represents a class. “string” is an alias for System.String. At execution time both are compiled to the same code. One more difference is the syntax highlighter.

Let us now check a code snippet to understand both of these.

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.Threading.Tasks;  
    namespace ConsoleApplication2  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                string FirstName = ".Net";  
                String Lastname = "Snippets";  
                Console.WriteLine(FirstName + " " + Lastname);  
                Console.ReadLine();  
            }  
        }  
    }  

@Mojtaba Nava 2019-09-21 15:18:58

One of the questions that many novice C# programmers ask is: “What is the difference between string and String?” In C#, string is an alias for the String class in .NET framework. 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 it is common practice to declare a variable using C# keywords. I’ve hardly seen anyone declaring an integer with Int32! The only tiny difference is that if you use the String class, you need to import the System namespace on top of your file, whereas you don’t have to do this when using the string keyword. Many developers prefer to declare a string variable with string but use the String class when accessing one of its static members:

String.Format()

@MicroservicesOnDDD 2019-08-16 14:11:33

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.

@mins 2019-09-20 10:11:03

"B. They are Different in Famework and in Non-C# Contexts": While this may be true, the answer doesn't tell what are the differences, it only lists the contexts where they can appear. Technically it doesn't answer the question, and unfortunately doesn't help more than the selected answer.

@mins 2019-10-05 13:34:41

"They are the SAME (exactly the same)": no, try this: string s = nameof (string) to be convinced.

@Ali Sufyan 2019-07-02 05:44:28

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

@Ted Mucuzany 2019-06-25 12:06:44

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).

@Ted Mucuzany 2019-07-04 13:28:41

As far as I know, string vs. String is a matter of coding style.

@Ted Mucuzany 2019-07-04 13:29:08

And string tends to win.

@aloisdg says Reinstate Monica 2019-04-11 08:39:47

@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 intrinsictly 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 code base would define a type of this name. Or that when String is defined it’s a sign of a bad code base.

[...]

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 code base. 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 post for archive reason. I ignore some parts, so I recommend to skip and to read the blog post if you can.

@Gonçalo Garrido 2019-05-14 15:15:12

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

String.Format()

Variable

string name = "";

@Prem Kumar Badri 2019-05-09 08:17:15

Difference between string and String in C#

One of the questions that many novice C# programmers ask is: “What is the difference between string and String?”

In C#, string is an alias for the String class in .NET framework. 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 it is common practice to declare a variable using C# keywords. I’ve hardly seen anyone declaring an integer with Int32!

The only tiny difference is that if you use the String class, you need to import the System namespace on top of your file, whereas you don’t have to do this when using the string keyword.

Many developers prefer to declare a string variable with string but use the String class when accessing one of its static members: String.Format()

Creating Type Aliases in C# : link

@rhughes 2019-04-17 19:16:35

This compiles:

public class MyClass<String>
{
}

This does not:

public class MyClass<string>
{
}

@BACON 2019-04-17 19:54:34

The String in MyClass<String> is not the String in the question (System.String class), though. It's a type parameter named String that will "hide" any unqualified usages of String the class (e.g. adding public String GetText() { return "Hello, World!"; } to that same generic class fails to compile). Evil code, that is.

@Derek Park 2008-08-10 07:22:02

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.

@Dominic Zukiewicz 2012-04-20 11:52:21

@JonSkeet - Like you, I prefer the aliased types. The Design Guidelines for Developing Class Libraries - General Naming Conventions recommends developers stick to the language specific naming, rather than the CLR type. They do so in the Convert methods, to save them re-defining it for every language.

@Jon Skeet 2012-04-20 12:24:48

@Dominic: That's in member names though, not implementation. I'm fine with (say) public int ReadInt32().

@Dominic Zukiewicz 2012-05-22 22:36:15

If you decide to use StyleCop and follow that, that will say to use the types specific to the language. So for C# you'll have string (instead of String), int (instead of Int32), float (instead of Single) - stylecop.soyuz5.com/SA1121.html

@Rob 2012-10-12 23:25:39

I always use the aliases because I've assumed one day it might come in handy because they are acting as an abstraction, so therefore can have their implementations changed without me having to know.

@JARRRRG 2014-05-12 23:04:24

Isn't the second example "`string greet = String.Format("Hello {0}!", place);" meant to have a capital S? String?

@Abhi 2014-12-15 17:46:22

One of the major advantage of String.Format that I have actually seen in real source code is when it's used this way, String.Format("The value of a is {0}", a); a being any variable declared and initialized. This way of formatting the strings have various advantages. One very simple example would be when say variable a is a value of a currency we can have £ or $ or whichever currency symbol formatted into the string.

@Sami Kuhmonen 2014-12-22 05:21:27

Visual Studio 2015 says that String.Format should be changed to string.Format, so I guess Microsoft is going that way. I have also always used String for the static methods.

@Klitos G. 2015-03-15 12:47:19

To add to the conversation I noticed that if you declare an object using String and not string, calling methods like Equals("text") or StartsWith("text") do not work and always return false.

@krowe2 2015-05-29 14:30:54

As I've read through these I've notice several of the comments are simply incorrect. @DRAirey1 In time, you'll find that the old way is still the best, if you doubt that then I dare you to try to write C# code without using Visual Studio. It's virtually impossible and a situation that does come up from time to time in web development work. @Vlad You don't need to import anything to use String. @Abhi Your comment is pointless and equally true for string.Format(). @KlitosG No, that isn't true. They all work exactly the same.

@Zesty 2015-07-23 07:09:32

I don't like the aliases. The class name feels logical to use (e.g. String.Format()), is generally more descriptive (e.g. Int32 vs int), and is immediately clear where it fits in the framework (within System). But it looks like MS wants us to use the aliases, so that's what we'll have to do.

@ruedi 2015-08-24 10:08:49

as a note to prevent confusion: Some c# to vb.net converter convert String(c#) to [String](vb) and string(c#) to string(vb).

@Waters 2015-08-25 13:24:36

I prefer the lowercase as the syntax color is different from classes and it gives me a feeling of using the builtin language features over something implemented.

@David Pine 2015-11-21 05:08:48

I always use the string alias, especially if I can avoid the "using System" statement. #lovesNegativeLinesOfCode

@Jeroen Vannevel 2016-02-05 20:38:26

Could you add a remark that there is, in fact, a difference? For example: nameof(string) won't compile whereas nameof(String) will.

@Broken_Window 2016-02-19 15:33:54

java needs these aliases, it gets angry when I use 'string' instead of 'String'. C# doesn't care.

@Żubrówka 2016-03-04 13:19:31

Sorry for the dumb question, but any idea of why do we need such alias?

@Razzer 2016-03-16 12:46:45

Visual Studio 2015 suggest string.Format

@beercohol 2016-05-04 15:41:14

@krowe2 In C# you have to include a using System; directive before you can refer to String in a class. Perhaps you're thinking of VB which does not seem to require an equivalent Imports directive.

@SparK 2016-06-02 12:53:20

Not exacly an alias as string is a global struct, not a class, that happens to be a wrapper around the System.String type.

@Vahid Amiri 2016-06-12 12:31:28

string should be used everywhere instead of String

@orad 2016-08-04 23:04:05

So everyone here is suggesting to do this? new string('-', 100) Ugh! I prefer to use BCL names when accessing static members such as Int32.Parse or when calling the constructor. Use aliases when you are specifying a type.

@O. R. Mapper 2017-01-12 12:57:59

@MikaelPuusaari: "If you reference Int16 instead of int, you will specify the type from the default Int32." - it is rather unclear what you are trying to say there (and actually, in that complete paragraph). Could you try to rephrase and/or provide a concrete example of what you mean (that illustrates how int vs. Int32 is different from string vs. String)?

@Jonathan Wood 2017-02-22 17:28:03

I used to prefer the syntax String.Format(), but the latest version of Visual Studio actually flags that as an expression that can be simplified. And when you simplify it, it just becomes string.Format(). So, as far as Visual Studio is concerned, string is always the preferred syntax when working with C#.

@Andy 2018-03-15 16:25:45

@SparK No, string is not a struct; it refers always to the class System.String. They are 100% identical in the IL.

@Max Barraclough 2018-05-22 14:18:21

Also, for type parameters with generics, MSDN examples favour List<string> over List<String>

@userSteve 2018-07-09 10:54:21

The key difference is string is guaranteed to always refer to System.String, whereas String could refer to a different class with the same name in a different namespace

@Franck 2018-10-03 14:27:27

@userSteve I have just been hit with that issue last August and it took a while to figure out it was the wrong namespace.

@RQM 2018-10-05 15:46:37

@Rob: I don't see your point. If string had its implementation changed in such a way that your program's behavior was changed, would you not like to know? If, however, the changes are such that your (and everyone else's) programs won't change behavior, why would String not have its implementation changed instead of string? Your additional layer of abtraction would only be of use if you were the one to control it, e.g. if you defined RobString to point to String for now, and maybe to something else of your liking at a later point in time. (Not that I necessarily recommend this.)

@Craig 2018-12-08 02:27:30

@userSteve That is an interesting example, and true. By the same token, if somebody hides the universal Base Class Library System.String type with a class named String in a tighter scope, they should be keelhauled. ;-)

@MikeB 2018-12-30 18:11:06

This answer says "generally recommended", but doesn't explain any justification for the recommendation, nor does it express when the "general" recommendations might not apply.

@aloisdg says Reinstate Monica 2019-04-11 08:51:01

On of the dev of the C# compiler wrote a blogpost on this subject, I shared it here.

@nullptr 2019-05-08 04:44:00

Nope, it's not fixed that the Int would be a fixed size of 32-bit/4-bytes. It could differ according to the processor architecture.

@phoog 2019-06-21 14:30:45

@nullptr there is no Int in C#. There is int. This cannot differ according to the processor architecture because it is one of several aliases for predefined struct types in the System namespace, and it represents System.Int32, which, as its name suggests, must be a 32-bit integer. The spec further specifies that "The int type represents signed 32-bit integers with values between -2147483648 and 2147483647." You may be thinking of C or C++.

@Backwards_Dave 2019-08-21 22:39:59

One thing to note is that String will work in any language that targets the .NET framework. Whereas string is a C# keyword. ie. you could more easily copy/paste C# code into a different language's code base if you used the .NET class names rather than the C# key words.

@René Carannante 2019-09-13 05:47:04

The all new Roslyn analytic tools (NuGet) suggest to use string for everything. Still I agree that you should only use string when refering to an object.

@claudioalpereira 2011-01-28 10:08:57

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.

@Braham Prakash Yadav 2018-12-01 17:44:23

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.

@Burak Yeniçeri 2018-10-16 17:32:14

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.

@Mel 2008-08-18 17:58:11

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.

@Taslim Oseni 2018-01-05 19:52:48

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

Like someone mentioned, it's just like bool and Boolean, not much difference..

@BerBar 2018-07-22 16:30:30

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.

@Jaider 2018-07-12 01:35:36

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!

@Luke Foust 2008-08-15 23:00:44

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.

@MauganRa 2015-06-15 15:37:29

The second point sounds actually like a reason not to use string, int etc.

@tomi.lee.jones 2015-09-15 17:48:00

@MauganRa And it's supposed to, the author of the book lists those reasons as to why he doesn't use aliases.

@Darryl 2015-09-21 22:11:04

"If someone is reading C# source code they should interpret long according to the language spec, not another languages spec." That misses the point entirely. It's not that anyone intends to misinterpret code, it's simply easy for one's brain to jump to the wrong conclusion when a type has a different meaning than what the programmer sees on a daily basis in another context. We all make mistakes; using explicitly named types makes those mistakes less likely.

@ps2goat 2016-08-31 04:15:22

@Darryl - I remember programming with .NET 1.x on Windows XP 32x. One of the kernel APIs required a long, and I kept getting overflow errors by using a .NET long for the struct I was passing in; it had to be a .NET int /Int32 to translate to the kernel's definition of a long. So there's still room for confusion! msdn.microsoft.com/en-us/library/windows/desktop/…

@gusgorman 2017-03-02 10:41:21

+These reasons sum up my feelings on the matter. When I first started coding in C# (coming from a Java/C++/C background) I thought the aliases were ugly. I still feel that way, unfortunately most of the world doesn't seem to agree with me, or they don't care, and so use the lowercase.

@jinzai 2017-11-13 19:17:48

The "bittedness" of an integer is reliant upon the compiler, not the language. The reason you get overflows using "long" is not because of the kernel, it is because of the compiler. Microsoft 16 bit compilers used a 16 bit integer size, 32 bit compilers used a 32 bit integer size. "string": is actually an "alias" for char*, but that is all out the window with .NET -- which is why IntPtr has no primitive equivalent -- no pointers.

@phoog 2018-02-08 14:30:36

@jinzai the question is about C#, in which long is defined as a signed 64-bit integer, regardless of the platform or the compiler. So in some cases at least, yes, it does depend on the language.

@Rudresha Parameshappa 2018-02-11 17:25:56

The best book till date I found is CLR via C#...`

@LuckyLikey 2019-07-30 09:37:57

what about var value = br.ReadSingle();?

@Həsən Cəfərov 2018-01-12 09:19:47

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

@zap92 2014-03-07 13:09:55

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.

@Pritam Jyoti Ray 2016-01-20 10:53:01

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#

@wild coder 2018-02-08 08:28:39

First of All, both(string & String) are not same. There is a difference: String is not a keyword and it can be used as 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 color):
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.".

@Heriberto Lugo 2018-02-14 16:13:14

so internally they are the same. meaning, they point to the same thing, and can be used interchangeably. their difference lies in that String is the name of the actual struct as defined, whereas string is an alias which points to that same struct. it (string) being an alias makes it a keyword, which is why VS shows them as difference colors. if you right click to view definition for string, you will be staring at the struct String.

@Ronnie 2008-08-10 07:26:14

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.

@Alan B 2015-03-16 16:32:52

Just pick one and be consistent. If you work somewhere with a house style, use that.

@aiodintsov 2016-02-24 06:51:16

unfortunately style is personal preference and may be too expensive to enforce in a large code base across several teams without dedicated code owner. there are always more important matters to take care of rather than string vs String. which brings us back to "more important things in life"

@PerpetualJ 2019-01-02 19:18:08

This is definitely a preference thing; for example: I prefer to use short, int, ushort, uint instead of Int16, etc. Mostly because this is how I learned. Granted, the Int16 is easier to immediately understand for those with less experience. +1 From me!

@v.slobodzian 2018-02-01 13:13:54

Jeffrey Richter written:

Another way to think of this is that the C# compiler automatically assumes that you have the following using directives in all of your source code files:

using int = System.Int32;
using uint = System.UInt32;
using string = System.String;
...

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.

@Jon Skeet 2008-10-18 18:52:13

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. 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:

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

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. The only primitive type which doesn't have an alias is System.IntPtr.

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 which 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.

@JaredPar 2008-10-19 02:00:57

The inheritance situation with enum is interesting. Can you point to documentation onto why alias must be used for enumerations? Or is this a known bug?

@Jon Skeet 2008-10-19 06:34:02

It's in section 14.1 of the spec (I can't quote here easily as it's too long). It doesn't explicitly say that you've got to use the alias, but the aliases are sort of treated as their own types. It's all a bit weird.

@Max Galkin 2010-05-11 17:08:40

"the aliases are all to value types" is said twice about different sets of aliases. Can't be true both times %)

@corsiKa 2011-09-09 21:27:44

@PiPeep what's more astounding than the large amount of upvotes is the staggering low amount of downvotes (consider the top 5 posts have a total of over 2000 upvotes, and yet only 1 downvote amongst them all). Especially when you factor in the notion that there's always "haters" in any community, I really find that simply incredible.

@King 2011-12-26 19:41:17

+1 for mentioning the enum situation. That's the real answer I would consider it to be. The enum in c# are not considered to be the integer(int) values like in c++. So you should either typecast it or convert it at declaration like @JonSkeet has mentioned it. Should you do this, then it has to be considered a 'type' . The keywords are alone considered which is in our case, a set of aliases of the original classes.

@phoog 2011-12-29 19:53:52

Your comment: "It doesn't explicitly say that you've got to use the alias, but the aliases are sort of treated as their own types. It's all a bit weird."

@Jon Skeet 2011-12-29 19:56:53

@phoog: Ah, sorry, I didn't realise you were referring to a comment. Yes, it's well-specified, I agree.

@Jon Skeet 2012-01-09 23:18:19

@pinusnegra: No, it's not - at least not in the same way as the others. You can't declare a method as returning System.Void for example. You can't use System.Void directly in C# like that.

@Peter Porfy 2012-01-09 23:34:53

@JonSkeet ahh, right :) I didn't check, just wondered, because I thought it's a keyword. Then what's the point of System.Void?

@Hussein Zawawi 2012-03-29 15:47:19

@JonSkeet "decimal is a value type, but not a primitive type in the CLR" can you please explain this idea more?

@Jon Skeet 2012-03-29 16:12:31

@HusseinX: Sure - look in the CLI spec and you'll see that there are no instructions for dealing with decimal. It's "just another value type" as far as the CLR is concerned.

@Sanjeev Rai 2013-06-05 07:09:27

One interesting difference between string and String is that string' is a keyword in c#, so you can not use it as a variable name.For Ex: string string="hi";//compiler error, but String String="hi";` is acceptable, as String is an identifire not a keyword.

@Jon Skeet 2013-06-05 07:18:18

@SanjeevRai: Yes. You can use @string to create an identifier which ends up as string though. It's a sort of escaping mechanism.

@Niels Keurentjes 2013-07-30 10:04:08

@PeterPorfy System.Void is used in reflection when inspecting methods without return values, for example in MethodInfo.ReturnParameter.

@Peter Porfy 2013-07-30 10:50:32

@NielsKeurentjes I got closer to the concept of void since by learning about the unit type of F#. Reflection also makes sense, thank you!

@sandeep talabathula 2014-01-18 05:00:45

When you do f12 on string or String it goes to the same String class metadata file.

@Adam Diament 2015-05-10 20:13:10

Thanks for the great explanation @JonSkeet! On a lighter note, I had a colleague a couple of years ago who preferred to use System.String because he liked the aqua colour that visual studio gives it better than the darker blue of 'string'!

@GRUNGER 2015-09-04 17:10:40

OK, but what makes people write String instead of string? Many open source code with String. Hm.

@Mafii 2016-06-02 07:43:44

@AdamDiment they should use ReSharper, this will make the fancy aqua fade out a bit because it says to use string instead of String ;)

@dasblinkenlight 2016-06-02 10:26:59

@JonSkeet It appears that the enums-must-use-alias requirement has been lifted either in C# 6 or some time before it (related question).

@SparK 2016-06-02 12:56:28

isn't uint a wrapper struct (like enum, around a class) and UInt32 a wrapper class (around a primitive)?

@Jon Skeet 2016-06-02 13:40:43

@SparK: No, not at all. And enums aren't wrappers around classes either. uint is only an alias for UInt32. They're exactly the same type, both structs (not classes).

@BanksySan 2018-01-18 13:40:59

There is one practical difference between string and String.

nameof(String); // compiles
nameof(string); // doesn't compile

This is because string is a keyword (an alias in this case) whereas String is a type.

The same is true for the other aliases as well.

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

@mins 2019-09-20 10:32:24

In the end someone able to state an actual difference... you may also add the need for a using System; directive prior to use String type instead of the C# keyword string. This should be the selected answer, or at least a highly voted one.

@Teter28 2014-12-30 13:43:08

You don't need import namespace (using System;) to use string because it is a global alias of System.String.

To know more about aliases you can check this link.

@Simon_Weaver 2009-02-24 05:14:10

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.

If for some reason you wanted a variable called string, you'd see only the first of these compiles:

StringBuilder String = new StringBuilder();  // compiles
StringBuilder string = new StringBuilder();  // doesn't compile 

If you really want a variable name called string you can use @ as a prefix:

StringBuilder @string = new StringBuilder();

Another critical difference: Stack Overflow highlights them differently.

@Roman Starkov 2013-08-19 10:30:07

Keep in mind that calling a local @string is really rather pointless, since the names of locals are only present in PDBs. Might as well call it _string or something. It makes more sense for things that have names accessible via reflection, where the name of an @string member would be "string".

@Elton 2015-10-27 15:16:54

Also keep in mind using a reserved word as a variable name is grossly inelegant.

@Matt Wilko 2016-07-04 15:14:19

The OP does not want to use String or string as a variable name. They asked for an explanation of the difference between these Types. Your answer only serves to add more confusion IMO

@Craig 2018-12-09 03:28:35

Why on earth would you even consider creating a variable that shadows the type name?

@Simon_Weaver 2018-12-09 03:31:28

@craig if you were writing software to teach people how to tie knots?

@Craig 2018-12-09 03:59:54

@Simon_Weaver knots in strings? haha, nice. :-) Of course, you could pick an alternative name, like thread. Wait a minute... D'oh!

@Jineesh Uvantavida 2017-11-10 11:34:20

A string is a sequential collection of characters that is used to represent text.

A String object is a sequential collection of System.Char objects that represent a string; a System.Char object corresponds to a UTF-16 code unit.

The value of the String object is the content of the sequential collection of System.Char objects, and that value is immutable (that is, it is read-only).

For more information about the immutability of strings, see the Immutability and the StringBuilder class section in msdn.

The maximum size of a String object in memory is 2GB, or about 1 billion characters.

Note : answer is extracted from msdn help section. You can see the full content here in msdn String Class topic under Remarks section

@DavidWainwright 2017-10-18 15:11:41

I prefer to use string because this type is used so much that I don't want the syntax highlighter blending it in with all the other classes. Although it is a class it is used more like a primitive therefore I think the different highlight colour is appropriate.

If you right click on the string keyword and select Go to definition from the context menu it'll take you to the String class - it's just syntactic sugar but it improves readability imo.

Related Questions

Sponsored Content

60 Answered Questions

[SOLVED] How to replace all occurrences of a string?

25 Answered Questions

[SOLVED] Case insensitive 'Contains(string)'

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

10 Answered Questions

[SOLVED] What are the correct version numbers for C#?

85 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

39 Answered Questions

3 Answered Questions

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

32 Answered Questions

[SOLVED] What is the difference between const and readonly in C#?

14 Answered Questions

[SOLVED] Convert JavaScript String to be all lower case?

  • 2008-09-30 20:22:35
  • Derek
  • 429497 View
  • 1260 Score
  • 14 Answer
  • Tags:   javascript string

Sponsored Content