Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Friday, May 25, 2012
What is the difference between String and string
In C#, what is the difference between String and string ? (note the case)
Example:
string s = "Hello, World";
String S = "Hello, World";
Also, what are the guidelines for the use of each?
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:
Apart from string, 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
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.
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..
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.
Valters, you cannot establish global aliases in the style of string, int, etc. so far as I know. However, you can do more localized aliasing for types and namespaces with the using keyword.
e.g.
using str = System.String; //... str s = "Now you've got another alias for string!";
See here: http://msdn.microsoft.com/en-us/library/sf0df423.aspx
'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.
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.
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.
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
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...
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.
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.
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.
‘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.
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 didn't get his opinion before I read the complete paragraph.
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.
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.
string is an alias for System.String. So technically, there is no difference. It's like int vs. System.Int32.
ReplyDeleteAs far as guidelines, I think 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.
Just for the sake of completeness, here's a brain dump of related information...
ReplyDeleteAs 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, 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
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.
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.
ReplyDeleteI can say the same about (int, System.Int32) etc..
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:
ReplyDeleteI'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.
It's been covered above; however, you can't use string in reflection; you must use String.
ReplyDeletestring and String are identical in all ways (except the uppercase "S"). There are no performance implications either way.
ReplyDeleteLowercase string is preferred in most projects due to the syntax highlighting
There IS one difference - you can't use String without "using System;" beforehand.
ReplyDeletestring is a reserved word, but String is just a class name.
ReplyDeleteThis means that 'string' cannot be used as a variable name by itself.
For instance if for some reason you were doing this :
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 : Stackoverflow highlights them differently.
Valters, you cannot establish global aliases in the style of string, int, etc. so far as I know. However, you can do more localized aliasing for types and namespaces with the using keyword.
ReplyDeletee.g.
using str = System.String;
//...
str s = "Now you've got another alias for string!";
See here: http://msdn.microsoft.com/en-us/library/sf0df423.aspx
'System.String' is THE .net string class - in C# 'string' is an alias for System.String - so in use they are the same.
ReplyDeleteAs 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.
string is just an alias for System.String. The compiler will treat them identically.
ReplyDeleteThe only practical difference is the syntax highlighting as you mention, and that you have to write using System if you use String.
C# is a language which is used together with the CLR.
ReplyDeletestring 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.
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).
ReplyDeleteConditional 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.
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
ReplyDeleteFYI
“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
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...
ReplyDeleteThis question was essentially covered here and here already.
ReplyDeleteI just wrote a short article on this topic, including a response from Juval Löwy (of IDesign, creator of the C# coding standard). It says it all!
ReplyDeleteCheck it out on this link.
Lower case string is an alias for System.String.
ReplyDeleteThey 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.
Using System types makes it easier to port between C# and VB.Net, if you are into that sort of thing.
ReplyDeleteString 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.
ReplyDeleteThere is no difference.
ReplyDeleteThe 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.
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.
ReplyDelete‘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.
ReplyDeleteI'd just like to add this to lfousts answer, from Ritchers book:
ReplyDeleteThe 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 didn't get his opinion before I read the complete paragraph.
There is no difference between the two - string, however, appears to be the preferred option when considering other developers' source code.
ReplyDeleteString (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.
ReplyDeleteIt'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.
ReplyDeleteTheoretically 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.