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

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

Example (note the case):

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

What are

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

    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

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

    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 type 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"?

    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 declared using "string". At the right hand side we are calling a method so "String" is more sensible.

    string s = String.ToUpper() ;
    
    0 讨论(0)
  • 2020-11-21 05:17

    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.

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

    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.

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

    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.

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

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

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