tags:

views:

5564

answers:

25

In C#, I want to initialize a string value with an empty string?

How should I do this? What is the right way, and why?

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

or ?

UPDATE

Thank you very much for your answers. It seems, that even the easiest questions can start quite interesting discussions.

+3  A: 

I personally prefer "" unless there is a good reason to something more complex.

MidnightGun
+1  A: 

Any of the above.

There are many, many better things to pontificate. Such as what colour bark suits a tree best, I think vague brown with tinges of dulcet moss.

Quibblesome
+2  A: 

I use the third, but of the other two the first seems less odd. string is an alias for String, but seeing them across an assignment feels off.

plinth
+1  A: 

The compiler should make them all the same in the long run. Pick a standard so that your code will be easy to read, and stick with it.

Chris Marasti-Georg
A: 

I think the second is "proper," but to be honest I don't think it will matter. The compiler should be smart enough to compile any of those to the exact same bytecode. I use "" myself.

Magus
+12  A: 

I'd prefer string to String. choosing string.Empty over "" is a matter of choosing one and sticking with it. Advantage of using string.Empty is it is very obvious what you mean, and you don't accidentally copy over non-printable characters like "\x003" in your "".

Jimmy
I'd argue that if you're accidentally copying non-printable characters into your code, you've got bigger problems than this question ;)
Jon Skeet
ASCII \003 happens to be a field delimiter for B2B Messages I've worked with :)
Jimmy
(I'd also suggest avoiding the \x escape, btw - it's too hard to spot the difference between "\x9Bad Compiler" and "\x9Good Compiler" which have *radically* different results!)
Jon Skeet
Personally I prefer String over string whenever calling a static method on String. I'm almost blind however and this is a personal preference that I don't enforce on anyonex.
Brett Ryan
+1  A: 

I doesn't make a difference. The last one is the quickest to type though :)

+6  A: 

String.Empty and string.Empty are equivalent. String is the BCL class name. string is the C#...shortcut if you will. Same as with Int32 and int. As far as "", nor really sure. Personally, I always use string.Empty.

Silviu Niculita
+1  A: 

Either of the first two would be acceptable to me. I would avoid the last one because it is relatively easy to introduce a bug by putting a space between the quotes. This particular bug would be difficult to find by observation. Assuming no typos, all are semantically equivalent.

[EDIT]

Also, you might want to always use either string or String for consistency, but that's just me.

tvanfosson
I agree with this remark, but I still live dangerously when I'm lazy. In any event, I don't think I have occasion to write code that uses a string before assigning to it outside of the variable declaration. In fact, it's annoying to me that I have to initialize my strings at all, despite the risks.
EnocNRoll
A: 

I don't know about String.Empty. If you use "" you will create a new string object and with string.Empty it doesn't happen.

Adones Cunha
You won't create a new string each time - there'll be one string interned across the whole assembly. If you care about the extra 20 bytes (roughly) then .NET isn't for you ;) Go with whatever's more readable...
Jon Skeet
Actually, a new string is created each time using quotes but the code is optimized in compilation time.
Adones Cunha
In what sense is a new string created each time then? The C' language spec explicitly says that it's interned. It's guaranteed *not* to create a new string each time.
Jon Skeet
C# language spec, even - sorry about the typo
Jon Skeet
I'm sorry. I've just read the spec and realized the mistake:"Each string literal does not necessarily result in a new string instance."page 98.
Adones Cunha
A: 

using an empty quoted string instantiates a new object. string.Empty does not. The difference is pretty minimal but technically string.Empty is more efficient.

theraccoonbear
Please see my response to Adones.
Jon Skeet
As my response said, "The difference is pretty minimal".
theraccoonbear
Yes, but your response also said "using an empty quoted string instantiates a new object" which is only true the first time for any particular interning scope (usually AppDomain, but sometimes assembly)
Jon Skeet
+2  A: 

string is synonym for System.String type, They are identical.

Values are also identical: string.Empty == String.Empty == ""

I would not use character constant "" in code, rather string.Empty or String.Empty - easier to see what programmer meant.

Between string and String I like lower case string more just because I used to work with Delphi for lot of years and Delphi style is lowercase string.

So, if I was your boss, you would be writing string.Empty

zendar
A: 

It doesn't matter - they are exactly the same thing. However, the main thing is that you must be consistent

p.s. I struggle with this sort of "whats the right thing" all the time.

Calanus
In the modern world, "consistent" means consistent across all teams world-wide, which is one of the StackOverflow's goals. If I may suggest, let's use String.Empty.
Pavel Radzivilovsky
A: 

I always use string.empty. Here is one explanation you might look at.

Scott
+3  A: 

The best code is no code at all and consequently, less code is better code.

Konrad Rudolph
Someone apparently doesn't like me …
Konrad Rudolph
I like your link. So I gave you an upvote, it was a good read. :)
Dave
+7  A: 

I wasn't going to chime in, but I'm seeing some wrong info getting tossed out here.

I, personally, prefer string.Empty. That's a personal preference, and I bend to the will of whatever team I work with on a case-by-case basis.

As some others have mentioned, there is no difference at all between string.Empty and String.Empty.

Additionally, and this is a little known fact, using "" is perfectly acceptable. Every instance of "" will, in other environments, create an object. However, .NET interns its strings, so future instances will pull the same immutable string from the intern pool, and any performance hit will be negligible. Source: Brad Abrams.

John Rudy
I don't see why "technically" every instance of "" will create an object. It's not just chance that strings are interned - it's in the C# spec.
Jon Skeet
+86  A: 

Use whatever you and your team find the most readable.

Other answers have suggested that a new string is created every time you use "". This is not true - due to string interning, it will be created either once per assembly or once per AppDomain (or possibly once for the whole process - not sure on that front). This difference is negligible - massively, massively insignificant.

Which you find more readable is a different matter, however. It's subjective and will vary from person to person - so I suggest you find out what most people on your team like, and all go with that for consistency. Personally I find "" easier to read.

The argument that "" and " " are esaily mistaken for each other doesn't really wash with me. Unless you're using a proportional font (and I haven't worked with any developers who do) it's pretty easy to tell the difference.

Jon Skeet
Your eyes can trick you when you are expecting to see "" you can easily mistake " " for "". This is why it is easier to edit something that someone else has written. Your brain doesn't have preconceived ideas about the text so it is easier to pick out the anonmalies.
tvanfosson
@tvanfosson: So have you (or a colleague) actually been bitten by this as a bug? I'm suspicious of this sort of claim without it actually having caused problems. I've been using "" for years without ever getting it wrong...
Jon Skeet
Jon, I use Segoe UI 10 pt in VS. Beautiful, tabs line up perfectly anyway, and I can have much-much longer lines this way. Maybe I'm not a developer then :D
Alan
...or I haven't worked with you, which is true, sadly ;)
Alan
@Alan: I will try that to see what it's like. Personally I use spaces instead of tabs (and will fight to the death to do so ;) which I suspect makes it work less well for lining up bits parameters etc... worth a try though.
Jon Skeet
I use string.Empty consistently, so no I haven't. On the other hand, I frequently edit my SO posts because I screw up and double type words that I don't see until after I've posted it. I'm just saying, why take the chance. And, no, I don't get paid by the character.
tvanfosson
Why take the chance? Because I find "" more readable than string.Empty. Otherwise I'd definitely use the latter. Given a definite personal preference vs a *potential* risk that has never bitten me, however, I think it's reasonable to go for the code that the team finds most readable.
Jon Skeet
@Jon: I use spaces instead of tabs, too, I didn't mean literal tabs but indentation. Sorry for that. And please do try it---I used to be a Courier New/Monaco/Lucida Sans Typewriter fan, but I tried Segoe UI once and never looked back :)
Alan
@Alan: Have changed for the moment. May well use this for presentations - nice to get more on the screen, particularly when the font is all blown up...
Jon Skeet
@Jon: If you read my answer, you'll see that I expressed a personal preference with, to me, a rational reason. You disagree. Perhaps when you hit your 40's and your near vision starts to degrade you may change your viewpoint. :-)
tvanfosson
@tvanfosson: I'll change my viewpoint when I see evidence that it causes a real rather than perceived problem :) I think that claiming it's relatively easy to introduce a bug when such a bug hasn't been seen is an overstatement. But yes, it's all personal opinion.
Jon Skeet
Personally, I've always used String.Empty, I use capital 'S' whenever I want to use a static method on string, it's just a personal prefference that allows me to distinguish a type from a variable. But this is just a carry-over from using StringUtils.EMPTY in commons.lang from java. One point of interest is I'm almost blind and this definately does help with readability for me.
Brett Ryan
@Brett: On the other hand, in Visual Studio "string" ends up in a different colour. As you say, it's personal preference...
Jon Skeet
You have given me the inspiration to start developing in Times New Roman.
Justin R.
I think the "problem" is not that it *introduces bugs* (I also never had that), but that it is *less readable* and that you sometimes have to *look twice* whether the string is initialized as an empty string `""` or a space `" "`. Certainly, it is pretty rare that a string is initialized to a space, but I still often check that unconsciously. Therefore, I always go with `String.Empty` because it is clear from the first sight.
gehho
@gehho: *You* find it less readable - and that's fine - but I find it *more* readable than `string.Empty`. Using a monospaced font, the difference between "" and " " is very clear to me, and `string.Empty` is unnecessarily cluttered. But it's really just personal preference.
Jon Skeet
@Jon: Absolutely - personal preference! I just wanted to reply to your comment from `Nov 4 '08 at 20:27` where you ask whether it ever introduced a bug. It is not that it introduces bugs, but that I (unconsciously) need more time to interpret it (it is (milli)seconds, but still...). And I think that others who mentioned this case (like tvanfosson and Brett Ryan) meant just that. I did not want to try to convince you to use `String.Empty` - I just wanted to explain the reason why some people prefer it. :)
gehho
① I use a proportional font and I have no trouble distinguishing `""` from `" "` (possibly depends on the font though); ② Even if it were hard to visually distinguish them, I think it would generally be clear from the code in context which one it should be.
Timwi
+1 for proportional font, but yeah, one needs to choose carefully or edit the font manually, since most have a space that's too narrow.
romkyns
A: 

While difference is very, VERY little, the difference still exist.

1) "" creates object while String.Empty does not. But this object will be created once and will be referenced from the string pool later if you have another "" in the code.

2) String and string are the same, but I would recommend to use String.Empty (as well as String.Format, String.Copy etc.) since dot notation indicates class, not operator, and having class starting with capital letter conforms to C# coding standards.

string.Empty *is* "", check the source
dss539
+1  A: 

I strongly prefer String.Empty, aside from the other reasons to ensure you know what it is and that you have not accidentally removed the contents, but primarily for internationalization. If I see a string in quotes then I always have to wonder whether that is new code and it should be put into a string table. So every time code gets changed/reviewed you need to look for "something in quotes" and yes you can filter out the empty strings but I tell people it is good practice to never put strings in quotes unless you know it won't get localized.

+1  A: 

Just about every developer out there will know what "" means. I personally encountered String.Empty the first time and had to spend some time searching google to figure out if they really are the exact same thing.

Jason Baker
It is a public readonly string field and its values is ""... why would that change?
Matthew Whited
A: 

Reflector says....

[Serializable, ComVisible(true)]
public sealed class String : IComparable, ICloneable, IConvertible,
    IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
{
    public static bool IsNullOrEmpty(string value)
    {
        if (value != null)
        {
            return (value.Length == 0);
        }
        return true;
    }

}
Matthew Whited
A: 

I'd suggest using String.IsNullOrEmpty().

kyoryu
A: 

hiee danimajo,

Please checkout the below link for further info . http://www.codeasp.net/articles/General%20.NET/106/difference-between-string-empty-and-doublequotes- Thanks

Monu
+42  A: 

Basically,

There really is no difference from a performance and code generated standpoint. In performance testing, they went back and forth between which one was faster vs the other, and only by milliseconds. In looking at the behind the scenes code, you really don't see any difference either. The only difference is in the IL, which string.Empty use the opcode "ldsfld" and "" uses the opcode "ldstr", but that is only because string.Empty is static, and both instructions do the same thing. If you look at the assembly that is produced, it is exactly the same.

C# Code

private void Test1()
{
    string test1 = string.Empty;    
    string test11 = test1;
}

private void Test2()
{
    string test2 = "";    
    string test22 = test2;
}

IL Code

.method private hidebysig instance void 
          Test1() cil managed
{
  // Code size       10 (0xa)
  .maxstack  1
  .locals init ([0] string test1,
                [1] string test11)
  IL_0000:  nop
  IL_0001:  ldsfld     string [mscorlib]System.String::Empty
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  stloc.1
  IL_0009:  ret
} // end of method Form1::Test1


.method private hidebysig instance void 
        Test2() cil managed
{
  // Code size       10 (0xa)
  .maxstack  1
  .locals init ([0] string test2,
                [1] string test22)
  IL_0000:  nop
  IL_0001:  ldstr      ""
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  stloc.1
  IL_0009:  ret
} // end of method Form1::Test2

Assembly code

        string test1 = string.Empty;
0000003a  mov         eax,dword ptr ds:[022A102Ch] 
0000003f  mov         dword ptr [ebp-40h],eax 

        string test11 = test1;
00000042  mov         eax,dword ptr [ebp-40h] 
00000045  mov         dword ptr [ebp-44h],eax


        string test2 = "";
0000003a  mov         eax,dword ptr ds:[022A202Ch] 
00000040  mov         dword ptr [ebp-40h],eax 

        string test22 = test2;
00000043  mov         eax,dword ptr [ebp-40h] 
00000046  mov         dword ptr [ebp-44h],eax
aBetterGamer
+1 great explanation. Please format the code though. (I would format it for you, but my rep is too low.)
dss539
PrateekSaluja
A: 

It is totally a code-style preference, do to how .NET handles strings. However, here are my opinions :)

I always use the BCL Type names when accessing static methods, properties and fields: String.Empty or Int32.TryParse(...) or Double.Epsilon

I always use the C# keywords when declaring new instances: int i = 0; or string foo = "bar";

I rarely use undeclared string literals as I like to be able to scan the code to combine them into reusable named constants. The compiler replaces constants with the literals anyway so this is more of a way to avoid magic strings/numbers and to give a little more meaning to them with a name. Plus changing the values is easier.

McKAMEY