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

后端 未结 30 3912
走了就别回头了
走了就别回头了 2020-11-21 04:35

Example (note the case):

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

What are

相关标签:
30条回答
  • 2020-11-21 05:09

    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

    0 讨论(0)
  • 2020-11-21 05:09

    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.

    0 讨论(0)
  • 2020-11-21 05:12

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

    0 讨论(0)
  • 2020-11-21 05:12

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

    0 讨论(0)
  • 2020-11-21 05:12

    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.

    0 讨论(0)
  • 2020-11-21 05:13

    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.

    0 讨论(0)
提交回复
热议问题