7486

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

string s = "Hello world!";
String s = "Hello world!";
Evorlor
  • 7,263
  • 17
  • 70
  • 141
Lance Fisher
  • 25,684
  • 22
  • 96
  • 122
  • 109
    @O.R.Mapper, but the fact remains that `string` is a *lexical* construct of the C# *grammar* whereas `System.String` is just a type. Regardless of any *explicit* difference mentioned in any spec, there is still this implicit difference that could be accomodated with some ambiguity. The language itself *must* support `string` in a way that the implementation is not (quite) so obligated to consider for a particular class in the BCL. – Kirk Woll Dec 02 '14 at 03:05
  • 146
    @KirkWoll: According to the language specification, the language itself *must* consider `string` to be exactly the same as the BCL type `System.String`, nothing else. That is not ambiguous at all. Of course, you can implement your own compiler, using the C# grammar, and use all of the tokens found like that for something arbitrary, unrelated to what is defined in the C# language specification. However, the resulting language would only be a C# lookalike, it could not be considered C#. – O. R. Mapper Dec 02 '14 at 08:22
  • 124
    You can use `string` without a using directive for System. You can't do that with `String`. – Wilsu Nov 30 '15 at 08:52
  • 1
    read about Boxing/Unboxing too btw. - https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx - "The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object" – George Birbilis May 10 '16 at 17:39
  • 27
    For someone coming from Algol and Fortran, this discussion shows there is something wrong with `string`. It is needed to abbreviate `System.String`, but, as an alias, it seems quite like, but not exactly the same thing. After several years of C#, though, I'd say, it is safe to simply use `string` and `string.Format()` and not to worry about `System.String`. – Roland Dec 20 '16 at 00:24
  • 1
    Since 2014 conventions have changed a lot in .net framework. Now there's no existence for String (capital s) while declaring variables. only alias string (small s) is available. Microsoft might wanted to remove confusing programming approach! – Sangeeta Nov 29 '18 at 09:53
  • 27
    @Sangeeta What are you saying? The `System.String` class is still there, and the `string` keyword is still an alias for it. Just like `System.Int32` and `int`. They are literally the same thing. – Craig Tullis Dec 08 '18 at 02:14
  • 1
    System.String myString = "Ha!"; @Wilsu No? I just did. – SacredGeometry Dec 31 '20 at 01:37
  • 1
    Essentially, there is no difference between string and String. String is a class in the .NET framework in the System namespace. The fully qualified name is System.String. Whereas, the lower case string is an alias of System.String. In my opinion I advise you to use string over String. However, depend on you . You can use any of them. I use System.String class to use any built-in string methods e.g., String.IsNullOrEmpty(). – luka Feb 04 '22 at 07:39
  • @SacredGeometry - no, you referenced System inline... so you did not. – Jesse Williams Jun 13 '22 at 17:23
  • @JesseWilliams I didn't use a "using directive" I just used an explicit namespace. So yes, I did. – SacredGeometry Jun 15 '22 at 15:20
  • @CraigTullis I think what he meant, is that Visual Studio will grey-out usage of `String`, and will suggest replacing it with `string`. Although I do remember some MSDN page saying that `string` should be used for params and variables, and `String` when using static methods – SimonC Jan 11 '23 at 12:42
  • @SimonC I wouldn't use String for static methods either. I dislike it, and there's no point in it. However; The System.String class is still the implementation of the native string data type, and "string" is an alias for it. I do like that the IDE flags it, but the downside to that is all of the massive roaming hordes of developers who routinely completely ignore that sort of thing, which ultimately just makes the code look even worse in the IDE with all of the grayed out junk and squiggly underlines all over the place. I have the same gripe with developers who ignore compiler warnings. – Craig Tullis Jan 11 '23 at 18:47
  • Oh no, I totally agree with you! That's just how I interpreted his comment and thought mentioning the (old) style was possibly of some value to someone here. – SimonC Jan 12 '23 at 09:04
  • In C#, string is an alias for System.String, which means they are the same type. The only difference is in the naming convention: string is written in lowercase, whereas String is capitalized. There is no difference in functionality or performance between string and String, so which one you use is entirely up to personal preference. However, the convention is to use string in C# code because it is more commonly used and looks cleaner. – Chiara Tumminelli Mar 11 '23 at 06:30
  • No difference. 'string' (lower case) is just an alias for System.String. – Darshan Adakane Mar 31 '23 at 09:07

66 Answers66

7020

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.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Derek Park
  • 45,824
  • 15
  • 58
  • 76
  • 197
    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) - http://stylecop.soyuz5.com/SA1121.html – Dominic Zukiewicz May 22 '12 at 22:36
  • 188
    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. – Rob Oct 12 '12 at 23:25
  • 63
    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. – Sami Kuhmonen Dec 22 '14 at 05:21
  • 5
    What do you say to the fact that you could define your own type “String” but can’t do the same for “string” as it’s a keyword, as explained in https://stackoverflow.com/questions/7074/what-is-the-difference-between-string-and-string-in-c/27965515#27965515 – jmoreno Oct 13 '20 at 21:37
  • 5
    I gues then... Just be conistent. Use string or String or use a cerntain one in a specific case, but always in that case. – Rob L Nov 29 '20 at 06:50
  • 3
    It's worth noting that `string` is not an alias for `String` but is an alias for `global::System.String`. When you use the alias, it is guaranteed to resolve to the system string type and not some other class called `String`. – John Wu Jan 13 '21 at 00:16
  • 2
    it is a bad practice for a language to have two different name for an exact same thing so i suggest microsoft to remove one of them – yılmaz Aug 31 '21 at 19:38
  • 2
    I personally like that using the lower case variants (such as `string`, `int` etc.) doesn't require importing the `System` namespace. – Snap Dec 10 '21 at 05:12
  • 2
    awsome exploration – HootanHT Mar 13 '22 at 13:10
  • Actually this `String` vs `string` is not a style only difference. As others pointed out `string` has a concrete meaning whereas `String` is normal identifier and all parsing, name resolution rules apply to it. C# compiler lead Jared Parsons has a very well blog post on this subject: https://blog.paranoidcoding.com/2019/04/08/string-vs-String-is-not-about-style.html – tbaskan Jan 21 '23 at 15:30
3791

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:

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • What does 'not a primitive type in the CLR' mean? That if you use decimals in your C# code, it won't be interoperable with other .NET languages like BASIC? – Haighstrom Aug 07 '22 at 12:14
  • @Haighstrom: It's not a matter of it not being interoperable - it's that the CLR instruction set doesn't have the concept of `decimal`. It's not a primitive type in that respect. – Jon Skeet Aug 07 '22 at 15:12
  • I guess my use of 'interoperable' was incorrect, but my question is what does `decimal` not being in the CLR mean on a practical level? i.e. what does writing `decimal` in my C# code stop me doing? It makes the .dll that I create from it CLS non-compliant, which means I can't import it into a BASIC project? – Haighstrom Aug 13 '22 at 19:28
  • 2
    @Haighstrom: As one example, it means that `decimal` values can't be used in attributes. (I don't believe the use of `decimal` is CLS-non-compliant though.) – Jon Skeet Aug 14 '22 at 08:27
825

String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference. Choose what you like and use that. If you code in C#, I'd prefer string as it's a C# type alias and well-known by C# programmers.

I can say the same about (int, System.Int32) etc..

Ry-
  • 218,210
  • 55
  • 464
  • 476
artur02
  • 4,469
  • 1
  • 22
  • 15
  • 17
    I personally prefer using "Int32", since it immediately shows the range of the value. Imagine if they upgraded the type of "int" on later higher-bit systems. 'int' in c is apparently seen as _"the integer type that the target processor is most efficient working with"_, and defined as "at least 16 bit". I'd prefer predictable consistency there, thank you very much. – Nyerguds Apr 28 '16 at 11:41
  • 8
    @MyDaftQuestions I concur. If anything it would make sense to *consistently use the .net types* because they are language ignorant and the type is obvious, independent of any language (do I know all of F#'s or VB's idiosyncrasies?). – Peter - Reinstate Monica Jan 21 '17 at 17:39
  • 24
    @Nyerguds There are two reasons to simply not worry about it. One is that `int` is defined in the C# language spec as a 32 bit integer regardless of the hardware. C#, despite a shared heritage in the mists of time, is not actually C. Changing `int` to a 64 bit integer would be a breaking change in the specification and the language. It would also require redefining `long`, as `long` is currently the 64 bit integer. The other reason not to worry is irrelevant since the types will never change, but .NET is just abstract enough that 99% of the time you don't have to think about it anyway. ;-) – Craig Tullis Dec 08 '18 at 02:47
  • 15
    @Craig I dig into lots of old proprietary game formats where I _do_ have to think about that all the time, though. And then using `Int16`, `Int32` and `Int64` is a _lot_ more transparent in the code than using the rather nondescriptive `short`, `int` and `long` – Nyerguds Dec 09 '18 at 02:29
  • 9
    But short, not, long, float, double, et al *are* descriptive, because they’re in the language spec. C# is not C. I prefer them on declarations because they’re concise, small, and aesthetically pleasing. I do prefer the Torre library names on API’s where the API has a data type dependency. – Craig Tullis Oct 14 '20 at 15:49
  • 1
    This is all tomato tomato. If I was doing something where I had to be counting bytes I would probably rely on `IntXX`, while in every other instance I would just use short int long, etc. I'm thankful that I can do *either* and I will leverage that flexibility to best serve my need. I also don't understand this argument because C/C++ does *not* use the intXX aliases at all, as far as I know C# did that on its own. Great low level discussion tho! – Narish Dec 28 '22 at 18:37
588

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.

Kols
  • 3,641
  • 2
  • 34
  • 42
Luke Foust
  • 2,234
  • 5
  • 29
  • 36
522

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.

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • 11
    string is also more efficient that String. It has fewer pixels, which consumes less energy. – Phil B May 06 '22 at 18:53
  • 5
    Important to note regarding @Phil B's comment. This is only relevant on OLED monitors when programming in dark mode. For LCD monitors or light mode, the energy consumed is identical. – Vapid Jun 14 '22 at 14:12
  • 5
    @VapidLinus Not exactly, on a LCD, energy is spent to hide an otherwise iluminated pixel, so more dark pixels means more energy spent! This is oposite to CRT monitors. So on light mode, OLED/CRT more pixels on the "S"=less energy, LCD more pixels on the "S"=more energy. Dark mode as you stated is the oposite. Although the measurement should be taken with a lot o precision, and the difference could be hidden in noise. – fbiazi Oct 24 '22 at 14:29
  • 1
    I think the energy spent during the time used to think about this is more than what can be saved by the difference here. – Paŭlo Ebermann Dec 20 '22 at 11:37
470

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

user3296
  • 389
  • 1
  • 2
  • 2
357

It's been covered above; however, you can't use string in reflection; you must use String.

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
TraumaPony
  • 10,742
  • 12
  • 54
  • 74
  • 23
    I do not understand what this answer means and why it was upvoted. You can use `typeof(string)` in reflection. Example one: `if (someMethodInfo.ReturnType == typeof(string)) { ... }` Example two: `var p = typeof(string).GetProperty("FirstChar", BindingFlags.NonPublic | BindingFlags.Instance);` Where is it that you must use `String`, not `string`? If you try things like `Type.GetType("String")` or `Type.GetType("string")`, neither will find the class because the namespace is missing. If for some *silly* reason you compare `.Name` of a type to `"string"` in a case-sensitive way, you are right. – Jeppe Stig Nielsen May 24 '19 at 12:04
  • Please explain. – Wouter Jul 21 '22 at 07:40
  • I don't think this is true. The compiler changes string into global::System.String so there's no reason string couldn't be used in reflection. – Plaje May 15 '23 at 13:02
312

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.

Erik Šťastný
  • 1,487
  • 1
  • 15
  • 41
Ronnie
  • 8,053
  • 6
  • 34
  • 34
248

I prefer the capitalized .NET types (rather than the aliases) for formatting reasons. The .NET types are colored the same as other object types (the value types are proper objects, after all).

Conditional and control keywords (like if, switch, and return) are lowercase and colored dark blue (by default). And I would rather not have the disagreement in use and format.

Consider:

String someString; 
string anotherString; 
Piyush
  • 18,895
  • 5
  • 32
  • 63
Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
223

string and String are identical in all ways (except the uppercase "S"). There are no performance implications either way.

Lowercase string is preferred in most projects due to the syntax highlighting

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
TheSoftwareJedi
  • 34,421
  • 21
  • 109
  • 151
222

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() ;
Troll
  • 1,895
  • 3
  • 15
  • 34
Shivprasad Koirala
  • 27,644
  • 7
  • 84
  • 73
217

C# is a language which is used together with the CLR.

string is a type in C#.

System.String is a type in the CLR.

When you use C# together with the CLR string will be mapped to System.String.

Theoretically, you could implement a C#-compiler that generated Java bytecode. A sensible implementation of this compiler would probably map string to java.lang.String in order to interoperate with the Java runtime library.

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189
194

Lower case string is an alias for System.String. They are the same in C#.

There's a debate over whether you should use the System types (System.Int32, System.String, etc.) types or the C# aliases (int, string, etc). I personally believe you should use the C# aliases, but that's just my personal preference.

Farid
  • 88
  • 13
urini
  • 32,483
  • 14
  • 40
  • 37
  • 7
    That's the problem, they are not 'C#' aliases, they are 'C' aliases. There is no native 'string' or 'int' in the C# language, just syntactic sugar. – Quark Soup May 29 '15 at 20:23
  • 20
    not sure where "C" came from here, since C# 5 language specification reads "The keyword string is simply an alias for the predefined class System.String." on page 85, paragraph 4.2.4. All high level languages are syntactic sugar over CPU instruction sets and bytecode. – aiodintsov Feb 24 '16 at 06:57
173

string is just an alias for System.String. The compiler will treat them identically.

The only practical difference is the syntax highlighting as you mention, and that you have to write using System if you use String.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Hallgrim
  • 15,143
  • 10
  • 46
  • 54
  • 21
    You do 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?)` – Ronald Oct 16 '09 at 17:53
161

Both are same. But from coding guidelines perspective it's better to use string instead of String. This is what generally developers use. e.g. instead of using Int32 we use int as int is alias to Int32

FYI “The keyword string is simply an alias for the predefined class System.String.” - C# Language Specification 4.2.3 http://msdn2.microsoft.com/En-US/library/aa691153.aspx

Farid
  • 88
  • 13
Pradeep Kumar Mishra
  • 10,839
  • 4
  • 25
  • 26
  • 2
    The link doesn't work. New link - [C# 6.0 specification 8.2.5.](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#825-the-string-type) – woojiq Mar 22 '22 at 10:21
135

As the others are saying, they're the same. StyleCop rules, by default, will enforce you to use string as a C# code style best practice, except when referencing System.String static functions, such as String.Format, String.Join, String.Concat, etc...

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
Lloyd Cotten
  • 4,416
  • 5
  • 23
  • 21
126

New answer after 6 years and 5 months (procrastination).

While string is a reserved C# keyword that always has a fixed meaning, String is just an ordinary identifier which could refer to anything. Depending on members of the current type, the current namespace and the applied using directives and their placement, String could be a value or a type distinct from global::System.String.

I shall provide two examples where using directives will not help.


First, when String is a value of the current type (or a local variable):

class MySequence<TElement>
{
  public IEnumerable<TElement> String { get; set; }

  void Example()
  {
    var test = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
  }
}

The above will not compile because IEnumerable<> does not have a non-static member called Format, and no extension methods apply. In the above case, it may still be possible to use String in other contexts where a type is the only possibility syntactically. For example String local = "Hi mum!"; could be OK (depending on namespace and using directives).

Worse: Saying String.Concat(someSequence) will likely (depending on usings) go to the Linq extension method Enumerable.Concat. It will not go to the static method string.Concat.


Secondly, when String is another type, nested inside the current type:

class MyPiano
{
  protected class String
  {
  }

  void Example()
  {
    var test1 = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
    String test2 = "Goodbye";
  }
}

Neither statement in the Example method compiles. Here String is always a piano string, MyPiano.String. No member (static or not) Format exists on it (or is inherited from its base class). And the value "Goodbye" cannot be converted into it.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • 1
    Your examples are slightly contrived, but only slightly. I would consider both to be indicative of design problems, but in legacy code it's quite conceivable. – ClickRick Sep 03 '21 at 22:47
  • Of course, if you got a variable named `string`, things also don't compile. – Paŭlo Ebermann Dec 20 '22 at 11:39
  • Such a name will have to be written as `@string` in C#. It means `string` seen as an ordinary identifier (not the keyword). It is not recommended to use names like `@string`, but if you need to access a member written in another .NET language where the name `string` is not special, the `@` trick becomes useful. – Jeppe Stig Nielsen Dec 21 '22 at 15:21
109

Using System types makes it easier to port between C# and VB.Net, if you are into that sort of thing.

Ishmael
  • 30,970
  • 4
  • 37
  • 49
98

Against what seems to be common practice among other programmers, I prefer String over string, just to highlight the fact that String is a reference type, as Jon Skeet mentioned.

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
RolandK
  • 490
  • 5
  • 15
  • Good point. If 'string' was not invented, we would not have any confusion and not need this pointless discussion. All our apps would just run fine with String. 'int' seems useful if you don't care about the bit size, which happens most of the time, and 'string' seems only added for consistency. – Roland Apr 20 '21 at 12:20
92

string is an alias (or shorthand) of System.String. That means, by typing string we meant System.String. You can read more in think link: 'string' is an alias/shorthand of System.String.

Andy
  • 8,432
  • 6
  • 38
  • 76
JeeShen Lee
  • 3,476
  • 5
  • 39
  • 59
90

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.

Otiel
  • 18,404
  • 16
  • 78
  • 126
80

String (System.String) is a class in the base class library. string (lower case) is a reserved work in C# that is an alias for System.String. Int32 vs int is a similar situation as is Boolean vs. bool. These C# language specific keywords enable you to declare primitives in a style similar to C.

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Joe Alfano
  • 10,149
  • 6
  • 29
  • 40
78

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.

Hossein
  • 3,083
  • 3
  • 16
  • 33
Mel
  • 2,337
  • 19
  • 25
78

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

Mihir Ajmera
  • 127
  • 1
  • 9
aloisdg
  • 22,270
  • 6
  • 85
  • 105
75

Coming late to the party: I use the CLR types 100% of the time (well, except if forced to use the C# type, but I don't remember when the last time that was).

I originally started doing this years ago, as per the CLR books by Ritchie. It made sense to me that all CLR languages ultimately have to be able to support the set of CLR types, so using the CLR types yourself provided clearer, and possibly more "reusable" code.

Now that I've been doing it for years, it's a habit and I like the coloration that VS shows for the CLR types.

The only real downer is that auto-complete uses the C# type, so I end up re-typing automatically generated types to specify the CLR type instead.

Also, now, when I see "int" or "string", it just looks really wrong to me, like I'm looking at 1970's C code.

Michael Ray Lovett
  • 6,668
  • 7
  • 27
  • 36
75

String is not a keyword and it can be used as Identifier whereas string is a keyword and cannot be used as Identifier. And in function point of view both are same.

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
user576533
  • 91
  • 2
  • 2
58

There is 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.

Similarly, int maps to System.Int32.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
52

There's a quote on this issue from Daniel Solis' book.

All the predefined types are mapped directly to underlying .NET types. The C# type names (string) are simply aliases for the .NET types (String or System.String), so using the .NET names works fine syntactically, although this is discouraged. Within a C# program, you should use the C# names rather than the .NET names.

user2771704
  • 5,994
  • 6
  • 37
  • 38
46

string is a keyword, and you can't use string as an identifier.

String is not a keyword, and you can use it as an identifier:

Example

string String = "I am a string";

The keyword string is an alias for System.String aside from the keyword issue, the two are exactly equivalent.

 typeof(string) == typeof(String) == typeof(System.String)
Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
Neel
  • 11,625
  • 3
  • 43
  • 61
  • 3
    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. – Techiemanu Mar 04 '18 at 09:29
45

Yes, that's no difference between them, just like the bool and Boolean.

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Coder
  • 1,923
  • 4
  • 18
  • 18
38

There is no difference between the two - string, however, appears to be the preferred option when considering other developers' source code.

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
Dot NET
  • 4,891
  • 13
  • 55
  • 98
30

One argument not mentioned elsewhere to prefer the pascal case String:

System.String is a reference type, and reference types names are pascal case by convention.

Zaid Masud
  • 13,225
  • 9
  • 67
  • 88
  • 5
    The casing conventions don't differ between reference types and value types, as evidenced by the `Int32` type you yourself mentioned. It doesn't make sense to eschew the keyword in favor of the class name to abide by some imagined restriction that reference types follow different naming conventions than value types. – P Daddy Apr 24 '13 at 15:34
26

Both are the same.The difference is how you use it. Convention is,

string is for variables

String is for calling other String class methods

Like:

string fName = "John";
string lName = "Smith";

string fullName = String.Concat(fName,lName);

if (String.IsNullOrEmpty(fName))
{
  Console.WriteLine("Enter first name");
}
Anuja Lamahewa
  • 897
  • 1
  • 11
  • 23
  • 3
    This convention is no more valid: if you use Visual Studio 2015 and try to use `String` the program suggests you to "simplify your code", carrying it to `string`. – Massimiliano Kraus Nov 04 '16 at 14:04
23

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
zap92
  • 269
  • 5
  • 17
23

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   |
BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • 1
    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. – mins Sep 20 '19 at 10:32
17

In case it's useful to really see there is no difference between string and System.String:

var method1 = typeof(MyClass).GetMethod("TestString1").GetMethodBody().GetILAsByteArray();
var method2 = typeof(MyClass).GetMethod("TestString2").GetMethodBody().GetILAsByteArray();

//...

public string TestString1()
{
    string str = "Hello World!";
    return str;
}

public string TestString2()
{
    String str = "Hello World!";
    return str;
}

Both produce exactly the same IL byte array:

[ 0, 114, 107, 0, 0, 112, 10, 6, 11, 43, 0, 7, 42 ]
Meer
  • 2,765
  • 2
  • 19
  • 28
tic
  • 2,484
  • 1
  • 21
  • 33
  • 2
    I've given you a +1, but your actual methods, when optimise+ is on, are identically `return "Hello World!";`. To actually ensure the types are "considered" you can use `return (string)(object)typeof(string).Name;` and `return (System.String)(System.Object)typeof(System.String).Name;`, which happens to confirm `System.Object` is identical to `object` too :-) – Mark Hurd Oct 26 '15 at 09:03
16

String refers to a string object which comes with various functions for manipulating the contained string.

string refers to a primitive type

In C# they both compile to String but in other languages they do not so you should use String if you want to deal with String objects and string if you want to deal with literals.

John Smith
  • 7,243
  • 6
  • 49
  • 61
Inverted Llama
  • 1,522
  • 3
  • 14
  • 25
16

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

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
  • 1
    Hi @MichaelAdams, thanks for pointing that out. What I mean was that `string` is the *shorthand* version of `System.String`. – Taslim Oseni Jul 14 '21 at 00:00
15

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.

Majid khalili
  • 520
  • 1
  • 4
  • 24
Teter28
  • 504
  • 5
  • 8
14

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

BanksySan
  • 27,362
  • 33
  • 117
  • 216
wild coder
  • 880
  • 1
  • 12
  • 18
  • 6
    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. – Heriberto Lugo Feb 14 '18 at 16:13
11

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.

BanksySan
  • 27,362
  • 33
  • 117
  • 216
hubot
  • 393
  • 5
  • 18
11

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;
BanksySan
  • 27,362
  • 33
  • 117
  • 216
Saurabh
  • 1,505
  • 6
  • 20
  • 37
10

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.

v.slobodzian
  • 453
  • 6
  • 16
9

String: A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object

string: The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework. string is the intrinsic C# datatype, and is an alias for the system provided type "System.String". The C# specification states that as a matter of style the keyword (string) is preferred over the full system type name (System.String, or String). Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

Difference between string & String:

  • The string is usually used for declaration while String is used for accessing static string methods
  • You can use 'string' do declare fields, properties etc that use the predefined type 'string', since the C# specification tells me this is good style.
  • You can use 'String' to use system-defined methods, such as String.Compare etc. They are originally defined on 'System.String', not 'string'. 'string' is just an alias in this case.
  • You can also use 'String' or 'System.Int32' when communicating with other system, especially if they are CLR-compliant. i.e. - if I get data from elsewhere, I'd de-serialize it into a System.Int32 rather than an 'int', if the origin by definition was something else than a C# system.
Geeky Ninja
  • 6,002
  • 8
  • 41
  • 54
9

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#

Pritam Jyoti Ray
  • 320
  • 1
  • 8
  • 12
8

In the context of MSDN Documentation, String class is documented like any other data type (e.g., XmlReader, StreamReader) in the BCL.

And string is documented like a keyword (C# Reference) or like any basic C# language construct (e.g., for, while, default).

Reference.

atiquratik
  • 1,296
  • 3
  • 27
  • 34
InfZero
  • 2,944
  • 4
  • 24
  • 36
8

As pointed out, they are the same thing and string is just an alias to String.

For what it's worth, I use string to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - int, bool, var etc (although Int32 and Boolean are also correct).

I use String when using the static methods on the String class, like String.Split() or String.IsNullOrEmpty(). I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.

yazan_ati
  • 263
  • 3
  • 3
8

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.

DavidWainwright
  • 2,895
  • 1
  • 27
  • 30
8

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

8

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

habib
  • 2,366
  • 5
  • 25
  • 41
Hasan Jafarov
  • 628
  • 6
  • 16
7

As far as I know, string is just an alias for System.String, and similar aliases exist for bool, object, int... the only subtle difference is that you can use string without a "using System;" directive, while String requires it (otherwise you should specify System.String in full).

About which is the best to use, I guess it's a matter of taste. Personally I prefer string, but I it's not a religious issue.

atiquratik
  • 1,296
  • 3
  • 27
  • 34
Kalu Singh Rao
  • 1,671
  • 1
  • 16
  • 21
7

String : Represent a class

string : Represent an alias

It's just a coding convention from microsoft .

sayah imad
  • 1,507
  • 3
  • 16
  • 24
7

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!

Jaider
  • 14,268
  • 5
  • 75
  • 82
7

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.

Sergio Rezende
  • 762
  • 8
  • 25
7

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.

6

string is an alias for String in the .NET Framework.

Where "String" is in fact System.String.

I would say that they are interchangeable and there is no difference when and where you should use one or the other.

It would be better to be consistent with which one you did use though.

For what it's worth, I use string to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - int, bool, var etc (although Int32 and Boolean are also correct).

I use String when using the static methods on the String class, like String.Split() or String.IsNullOrEmpty(). I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.

Vijay Singh Rana
  • 1,060
  • 14
  • 32
6

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.

Burak Yeniçeri
  • 91
  • 2
  • 15
5

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

String.Format()

Variable

string name = "";
Gonçalo Garrido
  • 126
  • 2
  • 11
5

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
  • 33
  • 1
  • 3
  • 8
5

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.

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
4

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.

4

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.

TRK
  • 188
  • 1
  • 7
2

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

Ahmad
  • 770
  • 9
  • 21
Ali Sufyan
  • 94
  • 1
  • 3
-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.

-4

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

Nima Habibollahi
  • 360
  • 5
  • 16
  • There's one opinion in there ;) Also most (if not all) editors with syntax highlighting will also highlight objects – SimonC Jan 11 '23 at 12:45
-8

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.

  • Well no, not in C#. They're literally - as defined per the specification - the same thing. [See documentation](https://learn.microsoft.com/en-us/dotnet/api/system.string?view=net-7.0) – SimonC Jan 11 '23 at 12:44