Difference between String (Uppercase s) and string (lowercase s)

HomeC#

Difference between String (Uppercase s) and string (lowercase s)

How to escape braces in a format string in C#
Building a String Encryption/Decryption Class in C#
Convert date string to DateTime object in C#

In C#, string (lowercase s) and String (uppercase S) are actually the same thing. They are both aliases for the System.String class, which represents a sequence of characters.

Here’s the breakdown:

  • string is a C# keyword, a shorthand alias for System.String. It’s the preferred way to declare string variables in C# code because it’s more concise and idiomatic.
  • String is the actual name of the class in the .NET Framework. You can use it interchangeably with string, but it’s generally less common in C# code.
    Why the two options?

C# provides aliases for some common types like string (for System.String), int (for System.Int32), and bool (for System.Boolean). This is mainly for convenience and readability. These aliases are more concise and align with the naming conventions of primitive types in C#.

Example:

Both of these declarations are equivalent and create a string variable with the value “Hello, world!”:

string greeting = "Hello, world!";
String greeting2 = "Hello, world!"; 

Key takeaway:

While you can technically use both, stick to string (lowercase) for declaring string variables in your C# code. It’s the standard convention and makes your code more readable and consistent.

COMMENTS

DISQUS: 0