3

What is the difference between these two declarations?

string str;
String str;
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
anjum
  • 2,363
  • 6
  • 28
  • 25

6 Answers6

22

In normal usage, string and String are identical; string is simply an alias for global::System.String. There are some edge-cases, though:

  • you need a using System; to use String - you don't for string
  • if you define a local class String {}, then String refers to that (this would be a silly thing to do, of course). You can't define a class called string (although @string is fine)
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3

There is no difference. string (lower case) is just an alias for System.String.

Viper
  • 2,216
  • 1
  • 21
  • 41
  • Yes, but `string` is *always* an alias for `System.String`, whereas `String` just follows the normal type lookup rules. If, for example, you have *another* class called `String` in the current scope, `String` will refer to *that*, and not to `System.String`. – Jörg W Mittag Aug 07 '10 at 11:28
2

string is a c# keyword. String is the System.String .NET type.

The C# compiler provided by MS maps the string keyword to the System.String .NET type, so they are equivalent.

Ani
  • 111,048
  • 26
  • 262
  • 307
2

Nothing really, in C# the type keywords actually are synonyms for the types. So int = System.Int32 short = System.Int16 and string = System.String.

heads5150
  • 7,263
  • 3
  • 26
  • 34
1

String is an alias for System.String object, so none.

System.String is a Common Type System type necessary for interaction with other .NET languages. "string" is just C# shortcut to this name (in the same way int is shortcut to System.Int32)

Matěj Zábský
  • 16,909
  • 15
  • 69
  • 114
-1

They are the same, no difference, string is simply an alias for the System.String type, there are other similar cases in C#, like int and System.Int32, long and System.Int64 (see another related question)

Curiously though, whilst you can use alias in your code in place of the fully qualified types, you still need to know the underlying type when you use the Convert class because there's no ToInt or ToLong methods but only ToInt32 and ToInt64..

Community
  • 1
  • 1
theburningmonk
  • 15,701
  • 14
  • 61
  • 104
  • 1
    Not as curious as it sounds: `Convert` is a framework class, not a language keyword. If it had methods named after the C# keywords, the methods would make no sense in VB or F# or other .NET languages. – Dan Puzey Aug 07 '10 at 10:47