-4

Possible Duplicate:
What is the difference between String and string

I have two scenarios where both a Struct and Class are acceptable, and I'm wondering what is the best practice.

Scenario 1:

public static String foo(){...}//String is a class

public static string foo(){...}//string is a struct

Scenario 2:

public foo(String bar){...}//String is a class

public foo(string bar){...}//string is a struct

What are the pros/cons to each implementation?

Community
  • 1
  • 1
s15199d
  • 6,187
  • 8
  • 38
  • 62
  • 9
    `string` is not a struct. It's an alias for the class `System.String`. – user703016 Aug 30 '12 at 14:09
  • 1
    `string` is a C# alias for `System.String` which is a class. It is not a struct. – gideon Aug 30 '12 at 14:09
  • Actually, there is a significant difference for the compiler (not very significant, but significant nonetheless). If you use the upper-case `String`, the compiler has to resolve it in the context of your `using` statements, to see whether you indeed meant `System.String` or perhaps `AdvancedPhysics.String` or `RememberToBuyButter.TieAroundFinger.String`. Lower-case `string`, on the other hand, is a keyword, and can only ever refer to `System.String`. – phoog Aug 30 '12 at 14:19

4 Answers4

5

The implementations are the same. String is a class, string is just alias.

For details see the following answer: What is the difference between String and string in C#?

Community
  • 1
  • 1
Artem Vyshniakov
  • 15,917
  • 2
  • 41
  • 47
  • phoog's comment makes this technically incorrect, but unless the OP is using a theoretical physics library it's extremely unlikely for String to be anything other than System.String, so it's correct in the most likely case. – KeithS Aug 30 '12 at 14:23
  • @KeithS nor for that matter, is it that likely that someone who could code a worthwhile theoretical physics library not spotting the downside of naming any .NET class `String`, at some point before they shipped. – Jon Hanna Aug 30 '12 at 14:35
  • Who knows, those string theorists are a loopy bunch (or so CBS tells me :P ). I seem to remember an episode where our heroes are trying to build a smartphone app, and have to kick Sheldon out of the development effort (mostly for being such a micromanager/ivory-tower type, but still). – KeithS Aug 30 '12 at 14:40
1

String and string are the same thing. They're both reference types, which means they are classes (little 's' string is an alias to the real class String).

I personally prefer using the class names instead of the aliases in my code. I guess I prefer the consistency between declaring variables of a certain type and then using static methods off those types (like String.Format).

David Hoerster
  • 27,332
  • 6
  • 63
  • 99
0

string is just an alias of String Type, the code MSIL is same

Aghilas Yakoub
  • 27,095
  • 4
  • 42
  • 47
0

String and string is same such as Int32 and int.

Kirill Bestemyanov
  • 11,721
  • 2
  • 20
  • 37