795

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 what?

RBT
  • 24,161
  • 21
  • 159
  • 240
Daniel Kreiseder
  • 12,135
  • 9
  • 38
  • 59
  • 7
    See also this similar discussion for java: http://stackoverflow.com/questions/213985/is-making-an-empty-string-constant-worth-it – harpo Nov 04 '08 at 20:05
  • What's more important, is never to compare a string to Sting.Empty.
    Bad: if(s == "")
    Good: if(s.Length == 0)
    – Pavel Radzivilovsky Dec 21 '09 at 10:35
  • 42
    better to use String.IsNullOrEmpty(string myString) though, surely? – ZombieSheep Dec 21 '09 at 10:36
  • 3
    I use [string.IsNullOrWhiteSpace(stringvalue)] ... works in .Net 4.0. To initialize, I simply use: [var text = "";] Simple, readable and takes the least time to type :) – Jalal El-Shaer Oct 07 '11 at 12:51
  • 80
    What's more important is the hilarious name of your variable. – Arj Nov 29 '11 at 10:34
  • 5
    The thing that has interested me, is why is there even an Empty property. It is nice and everything, but not a necessary and a complete must. – MasterMastic Apr 18 '12 at 14:28
  • possible duplicate of [What is the difference between String.Empty and "" (empty string)?](http://stackoverflow.com/questions/151472/what-is-the-difference-between-string-empty-and-empty-string) – nawfal Jun 29 '13 at 07:22
  • there _was_ a difference https://stackoverflow.com/questions/16618302/changed-behavior-of-string-empty-or-system-stringempty-in-net-4-5 – Logerfo Sep 14 '17 at 12:24
  • 2
    @ZombieSheep You can't use IsNullOrEmpty to set the value of a string variable... – Stewart Feb 26 '18 at 15:59
  • 1
    Also, if you use code obfuscation. string.empty can be obfuscated where as "" won't be obfuscated. Again, not a huge difference nor will it matter that much if you are using some sort of obfuscation but it is a difference. – Jack Apr 30 '18 at 18:45

30 Answers30

880

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

Otiel
  • 18,404
  • 16
  • 78
  • 126
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 83
    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 Nov 04 '08 at 20:18
  • 144
    @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 Nov 04 '08 at 20:27
  • 6
    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 Nov 04 '08 at 20:29
  • 20
    @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 Nov 04 '08 at 20:50
  • 1
    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 Nov 04 '08 at 22:19
  • 5
    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 Nov 04 '08 at 22:25
  • @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 Nov 04 '08 at 22:40
  • @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 Nov 04 '08 at 23:04
  • @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 Nov 05 '08 at 03:49
  • 1
    @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 Nov 05 '08 at 12:35
  • 35
    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 Sep 11 '09 at 04:34
  • @Brett: On the other hand, in Visual Studio "string" ends up in a different colour. As you say, it's personal preference... – Jon Skeet Sep 11 '09 at 05:24
  • 87
    You have given me the inspiration to start developing in Times New Roman. – Justin Rusbatch Feb 21 '10 at 18:39
  • 4
    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 Aug 31 '10 at 06:52
  • 6
    @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 Aug 31 '10 at 07:54
  • @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 Aug 31 '10 at 09:46
  • 1
    ① 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 Sep 16 '10 at 09:37
  • +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. – Roman Starkov Sep 16 '10 at 09:48
  • 2
    `""` looks not much like `" "`, but it could possibly be confused with `'"'`. – Ben Voigt Nov 18 '10 at 03:40
  • 1
    @Ben: Can't say I've ever had a problem with that... especially as in many cases it wouldn't be valid due to the different type. – Jon Skeet Nov 18 '10 at 06:32
  • 15
    Personally, I find my brain uses much less power interpreting a simple pattern `""` than String.Empty ("hey, there's a class and a property - what's it doing?") Does everyone who uses String.Empty also use String.Space(1)? If no space is hard to distinguish, then one or more might be also. – goodeye Jan 08 '12 at 02:34
  • 3
    The only probable point of confusion is between one double-quote and two single quotes... (" vs '') == WTF!?!?! Any "competent" programmer will deal equally easily with EITHER var s="" OR var s=String.Empty. But reading through the comments herein... it's nice to see confirmation that other folks have pathalogical, quasi-religious beliefs about program style, that really don't matter a rats bumpkin. I thought I was alone. Sigh. – corlettk Feb 17 '12 at 04:24
  • 17
    The biggest advantage of string.Empty is that you can more easily find the precise usages of it in an IDE such as Visual Studio. A simple "find" operation for "" will return escaped quotes and "" representation in comments as well as the usages you're actually looking for. Doing a code-inspection type of "find usages" of string.Empty will get you all of the usages of it solution-wide, where as finding usages of a string literal (like "") is limited to the scope of the assembly it's defined in. – MutantNinjaCodeMonkey Jun 22 '12 at 18:28
  • 7
    @MutantNinjaCodeMonkey: I can't remember ever searching for "" across a codebase, and if I did, my uses of "" in comments or verbatim string literals is sufficiently small that it wouldn't bother me much. If that's really the biggest advantage of `string.Empty`, it's a pretty miniscule one IMO. – Jon Skeet Jun 22 '12 at 18:50
  • 4
    Debating on programming preferences is like debating on food preferences. It is impossible to prove one better than the other, because there is no _practical_ difference to those using it. It is certain that the consistent use of one over the other, will definitally cause to the less adaptive sort a bit of difficulty when they had to change their habbits, but, in truth, variaety is supposed to give each person freedom to develop its own style, although this freedom of choice has led to more wars(both armed and flame) than anything else. – ThunderGr Dec 12 '12 at 11:54
  • 90
    For some [obscure reason `string.Empty` is not a constant](http://stackoverflow.com/questions/507923/). That means that in a number of cases where a compile-time constant is required, `string.Empty` isn't even legal. This includes `case ""` blocks in **`switch`** statements, default values of **optional parameters**, parameters and properties in applying **attributes**, and a lot of other situations (left to the reader). So given that `string.Empty` is disallowed in some common situations, it is better to use the `""`-everywhere convention. – Jeppe Stig Nielsen May 10 '13 at 21:20
  • 4
    I also develop in Javascript, VBScript, SQL, and VB6... and while string.Empty may only work in .Net, "" (or '') works everywhere. I like using the "", just for consistency across different languages in the same product. – TomXP411 Jul 17 '14 at 20:30
  • The Visual Studio 2015 update 3 C# editor's "Quick Actions" feature suggests to always "simplify" `String.Empty`, all over the place. when I accept the suggestion, it is converted to `string.Empty`. Would be interesting to know the rationale behind that. – Cee McSharpface Aug 09 '16 at 19:16
  • _(and I haven't worked with any developers who do)_ well, I don't understand how people can use other fonts then Verdana for the sourcode ;-] – t3chb0t Jan 30 '17 at 13:20
  • I had a PR issue asking me to change " " with string.Empty. Probably the most pedantic PR issue ever. – xleon Oct 01 '20 at 21:01
  • _"due to string interning, it will be created either once per assembly or once per AppDomain"_ That's true. But this possibly large pool has to be looked up everytime you use `""` instead of `string.Empty`. While this is micro optimization in most cases, it's worth noting that it's wasting cpu cycles. Or do current compilers replace `""` with `string.Empty` behind the scenes? – Tim Schmelter May 17 '21 at 17:00
  • @TimSchmelter: When you say "everytime you use `""`" - I'd expect it to be once per time the string literal is used, per assembly load. So if you've got a method called in a loop, and that method uses `""`, it's not going to check it on every iteration of the method. I think the number of CPU cycles wasted here is likely to be utterly insignificant in the vast, *vast* majority of cases. – Jon Skeet May 17 '21 at 17:06
  • @JonSkeet: Thanks, i was afraid that it needs to be looked up every time it is used. I just read that since .NET 4.5 "ldstr "" is replaced with ldsfld string [mscorlib]System.String::Empty by the jitter" anyway. – Tim Schmelter May 17 '21 at 17:10
  • After reading this, all I want to do is create a font that has a ligature to replace "" with string.Empty. For the LOLs of course – Michael Meadows May 27 '23 at 16:18
399

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 
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
aBetterGamer
  • 5,119
  • 2
  • 18
  • 19
  • 14
    @PrateekSaluja: To see the IL you can use ildasm.exe, which ships with Visual Studio. To see diassembly, use the 'Disassembly' window on the debug menu when you hit a breakpoint (works in release code too). – Thomas Bratt Jan 08 '12 at 18:23
  • 1
    Hate that i am about to recommend this product.. BUT .. reflector lets you choose your language when disassembling the source and IL is an option! ILDASM is just dated feeling... MS tools team does not seem to polish or release the good tools! – felickz Jan 19 '12 at 15:00
91

The best code is no code at all:

The fundamental nature of coding is that our task, as programmers, is to recognize that every decision we make is a trade-off. […] Start with brevity. Increase the other dimensions as required by testing.

Consequently, less code is better code: Prefer "" to string.Empty or String.Empty. Those two are six times longer with no added benefit — certainly no added clarity, as they express the exact same information.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    but in C# we can just say string.IsNullOrWhitespace(s) :p – felickz Jan 19 '12 at 15:04
  • 42
    I agree that code should be as small as possible but wouldn't generally argue that less characters is always better code. When it comes to variable naming for example, a reasonable amount of characters generally result in better names than just using i and j. – Markus Meyer Mar 28 '13 at 11:23
  • 3
    @Markus That highly depends: for a loop variable representing an index, `i` *is* better than a long variable name. Even more general, shorter variable names *that convey the same information*, in the same clarity, are always preferable. It’s just that to express the necessary information you *need* a certain character length, and I’m not denying this (nobody is). – Konrad Rudolph Mar 28 '13 at 11:29
  • 2
    @Konrad: i is a good variable name only if the loop is small and it doesn't contain any other indices. But I agree that if sth. can be stated more briefly conveying the same information, that would be preferrable, like in the string.Empty / "" case. The string.Empty does not add any clarity. – Markus Meyer Mar 28 '13 at 13:01
  • 2
    To me: string.Empty says this string is and should be Empty at all times, whereas "" says at the time of writing this string could be empty but you are free to change it. – aeroson Aug 13 '17 at 13:59
  • 1
    @aeroson Feel free to interpret everything the way you want but be aware that nobody else will share your highly idiosyncratic reading, and thus don’t rely on it to communicate intent: Nobody will get it. – Konrad Rudolph Aug 14 '17 at 09:55
  • 1
    @aeroson Strings are immutable, so there is no changing them. If you are referring to changing what is in the _variable_, I would not presume such an intent from what is initially assigned to that variable. – Timo Sep 24 '18 at 08:54
  • 1
    Brevity should always be trumped by readability. There is a reason why the framework developers added `String.Empty` and that wasn't just for performance issues but also to make it very clear what the intent is. Whilst scanning through code it's much easier to identify (and search for) than `""`. – Dan Diplo Oct 17 '18 at 15:32
  • 1
    @DanDiplo You cannot seriously argue that `String.Empty` is more readable than `""`. It plain *isn’t*, and contrary to your claim there’s no evidence that the framework developers think so (I can’t read their minds but I’m pretty sure that they don’t think that and that, if anything, they probably see its presence as a mistake in hindsight). Let’s ping Eric Lippert — although the chances of reading this are probably slim. – Konrad Rudolph Oct 18 '18 at 01:04
  • @KonradRudolph In Microsoft's recent examples for "Best Practices Using String in .NET Framework" they use `String.Empty` - see https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#recommendations_for_string_usage – Dan Diplo Oct 18 '18 at 14:26
  • 1
    @Dan Diplo They USE it but they don't EXPLAIN it. So you can safely consider it a coincidence. – The incredible Jan Nov 16 '22 at 12:36
60

One difference is that if you use a switch-case syntax, you can't write case string.Empty: because it's not a constant. You get a Compilation error : A constant value is expected

Look at this link for more info: string-empty-versus-empty-quotes

Kols
  • 3,641
  • 2
  • 34
  • 42
Mentoliptus
  • 2,855
  • 3
  • 27
  • 35
  • 25
    The `switch` statement is one very good example. Also, if you make an optional parameter, like `void MyMethod(string optional = "") { ... }`, it's also not possible to use `string.Empty`. And then of course if you want to define a `const` field or local variable, `const string myString = "";` the again `""` is the only option. If only `string.Empty` were a constant field, there wouldn't be a difference. But it's not, so in some cases you have to use `""`. So why not use `""` all the time? – Jeppe Stig Nielsen Oct 29 '12 at 21:19
  • 5
    This is a really strong argument because using `string.Empty` prevents you from attaining **consistency** in your code base: you must use two different entities to express the same thing. And to add to the list of things you can't do: you can't use `string.Empty` with **attributes**. – Pragmateek Nov 07 '13 at 22:03
  • 2
    Very good points! The link is broken. Here's a copy of the content: http://web.archive.org/web/20131230161806/http://kossovsky.net/index.php/2009/06/string-empty-versus-empty-quotes/ – ygoe Feb 13 '15 at 15:37
  • 1
    Sam issue with default arguments in functions. Needs to be a compile-time constant! – James Heazlewood Aug 05 '23 at 02:57
48

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

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
Jimmy
  • 89,068
  • 17
  • 119
  • 137
  • 110
    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 Nov 04 '08 at 20:10
  • 10
    ASCII \003 happens to be a field delimiter for B2B Messages I've worked with :) – Jimmy Nov 04 '08 at 21:06
  • 8
    (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 Nov 04 '08 at 21:39
  • 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 anyone. – Brett Ryan Sep 11 '09 at 04:42
  • I would probably declare a const over `"\x003"`. :) – Andy Nov 12 '12 at 20:07
  • I've been bitten by something similar, where I've got a document with strings with unprintable characters in a new job ... :) – Noctis Nov 04 '14 at 06:43
  • 3
    You use copy/paste to type `""`...? – Timo Nov 10 '15 at 08:38
  • @Timo Don't take the example literally. Pretend it was copying a blob of text with embedded non-printable characters from API documentation. – Jimmy Nov 10 '15 at 22:35
  • 3
    @Jimmy Sure, but we were talking about the empty string. The argument that `""` is dangerous when copy/pasting is void, I claim, because you never copy/paste the empty string. For other strings, it is always something to be mindful of, of course. – Timo Nov 12 '15 at 09:11
  • @Jimmy Why there are non-printable characters in a DOCUMENTATION?! That sounds so wrong... – The incredible Jan Nov 16 '22 at 12:43
24

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.

Brian Leahy
  • 34,677
  • 12
  • 45
  • 60
John Rudy
  • 37,282
  • 14
  • 64
  • 100
  • 24
    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 Nov 04 '08 at 20:09
  • 1
    There is a difference between `string.Empty` and `String.Empty`. The first uses the C# language keyword `string` so it always works. The latter only works with `using System;` in the file. Prefer `string` over `String` always. – Aaron Franke Jun 01 '22 at 21:00
16

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

MidnightGun
  • 1,006
  • 1
  • 19
  • 39
16

This topic is pretty old and long, so excuse me if this behavior has been mentioned somewhere else. (And point me to the answer that covers this)

I have found a difference in the behavior of the compiler if you use string.Empty or double quotes. The difference shows itself if you don't use the string variable initialized with string.Empty or with double quotes.

In case of initialization with string.Empty then the Compiler Warning

CS0219 - The variable 'x' is assigned but its value is never used

is never emitted while in case of initialization with double quotes you get the expected message.

This behavior is explained in the Connect article at this link: https://connect.microsoft.com/VisualStudio/feedback/details/799810/c-warning-cs0219-not-reported-when-assign-non-constant-value

Basically, if I get it right, they want to allow a programmer to set a variable with the return value of a function for debugging purposes without bothering him with a warning message and thus they limited the warning only in case of costant assignments and string.Empty is not a constant but a field.

SOME YEARS AFTER
Microsoft has retired the https://connect .microsoft.com website so the discussion there is no more available. However there is this article https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0219 with an interesting remark that seems to confirm the previous reasons:

The compiler generates this warning only when the variable value is a compile-time constant. Assigning a non-constant expression or method result to a local variable makes it easier to observe those expressions in the debugger. It also makes the result reachable, preventing garbage collection while that variable is reachable.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    I believe you’re the first one to mention. I have read through this Q&A several months ago and don’t remember this difference, which I would if it had been mentioned. – Palec Apr 30 '16 at 08:46
  • 3
    Interesting. Note that a declaration `var unused = "literal";` can be completely optimized away (removed) by the compiler. It can have no side effects. On the other hand, `var unused = MyClass.Member;` cannot be removed entirely. That is because reading `Member` could have side effects. If `Member` is a static property with a `get` accessor, it is clear that the call to the getter must be kept. But even if `Member` is a static field, there may be the side effect that the static constructor may run. Sure it would be _bad coding style_ to have it that way. But you need a dummy to read `Member`. – Jeppe Stig Nielsen Jan 30 '17 at 22:03
15

String.Empty and string.Empty are equivalent. String is the BCL class name; string is its C# alias (or shortcut, if you will). Same as with Int32 and int. See the docs for more examples.

As far as "" is concerned, I'm not really sure.

Personally, I always use string.Empty.

Palec
  • 12,743
  • 8
  • 69
  • 138
15

I performed a simple test using following method in a .NET v4.5 console application:

private static void CompareStringConstants()
{
    string str1 = "";
    string str2 = string.Empty;
    string str3 = String.Empty;
    Console.WriteLine(object.ReferenceEquals(str1, str2)); //prints True
    Console.WriteLine(object.ReferenceEquals(str2, str3)); //prints True
}

This suggests that all three variables namely str1, str2 and str3 though being initialized using different syntax are pointing to the same string (of zero length) object in memory .

So internally they have no difference. And it all boils down to convenience of which one you or your team wants to use. This behavior of string class is known as string interning in .NET Framework. Eric Lippert has a very nice blog here describing this concept.

RBT
  • 24,161
  • 21
  • 159
  • 240
11

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
  • 192,085
  • 135
  • 376
  • 510
9

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
  • 25,225
  • 10
  • 61
  • 100
7

No one mentioned that in VisualStudio String is color coded differently then string. Which is important for readability. Also, lower case is usually used for vars and type, not a big deal but String.Empty is a constant and not a var or type.

Dimitry
  • 71
  • 1
  • 1
  • 1
    String.Empty is not a constant: see https://stackoverflow.com/questions/507923/why-isnt-string-empty-a-constant It's actually an instance of the String class, by design. And coloring was mentioned before though a bit hidden: https://stackoverflow.com/questions/263191/in-c-should-i-use-string-empty-or-string-empty-or-to-intitialize-a-string#comment1251042_263257 – Michael Oct 30 '19 at 07:26
7

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
  • 13,384
  • 14
  • 59
  • 75
  • I write "" if I mean "" and I assume that others also write what they mean - otherwise it's a bug. If you care about string.Empty as a boss you newer would be my boss and your company probably wouldn't exist very long. :) – The incredible Jan Nov 16 '22 at 12:56
7

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.

5

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

5

I would favor string.Empty over String.Empty because you can use it without needing to include a using System; in your file.

As for the picking "" over string.Empty, it is personal preference and should be decided by your team.

RBT
  • 24,161
  • 21
  • 159
  • 240
Andrew
  • 144
  • 2
  • 4
  • 3
    I'm the only member of the team, how do I decide? throw a dice? – Gqqnbig Jun 20 '17 at 22:37
  • 2
    For those who might be wondering as to how it is possible to use `string.Empty` constant without importing `using System` namespace - Keywords in C# simply get converted to their fully qualified name which includes the namespace as well before being written as MSIL in the output *.dll or *.exe file. So effectively `string.Empty` gets written as `System.String.Empty` in the MSIL by the compiler. And as you already might be knowing that if you mention fully qualified type name then you can give a skip to importing namespaces at the top of your code file. – RBT Aug 26 '17 at 03:13
5

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
  • 17,359
  • 16
  • 83
  • 116
4

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
  • 524,688
  • 99
  • 697
  • 795
  • 1
    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 - AnandaGopal Pardue Jan 28 '09 at 16:55
4

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
  • 25,619
  • 25
  • 85
  • 120
4

I have personally witnessed "" resulting in (minor) problems twice. Once was due to a mistake of a junior developer new to team-based programming, and the other was a simple typo, but the fact is using string.Empty would have avoided both issues.

Yes, this is very much a judgement call, but when a language gives you multiple ways to do things, I tend to lean toward the one that has the most compiler oversight and strongest compile-time enforcement. That is not "". It's all about expressing specific intent.

If you type string.EMpty or Strng.Empty, the compiler lets you know you did it wrong. Immediately. It simply will not compile. As a developer you are citing specific intent that the compiler (or another developer) cannot in any way misinterpret, and when you do it wrong, you can't create a bug.

If you type " " when you mean "" or vice-versa, the compiler happily does what you told it to do. Another developer may or may not be able to glean your specific intent. Bug created.

Long before string.Empty was a thing I've used a standard library that defined the EMPTY_STRING constant. We still use that constant in case statements where string.Empty is not allowed.

Whenever possible, put the compiler to work for you, and eliminate the possibility of human error, no matter how small. IMO, this trumps "readability" as others have cited.

Specificity and compile time enforcement. It's what's for dinner.

GabrielMCS
  • 15
  • 1
  • 6
RhinoTX
  • 169
  • 3
3

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
  • 48,267
  • 11
  • 78
  • 120
3

I was just looking at some code and this question popped into my mind which I had read some time before. This is certainly a question of readability.

Consider the following C# code...

(customer == null) ? "" : customer.Name

vs

(customer == null) ? string.empty : customer.Name

I personally find the latter less ambiguous and easier to read.

As pointed out by others the actual differences are negligible.

Remotec
  • 10,304
  • 25
  • 105
  • 147
2

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
  • 34,091
  • 15
  • 92
  • 137
2

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

  1. "" creates an 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.

janw
  • 8,758
  • 11
  • 40
  • 62
user34577
  • 83
  • 1
  • 5
2

I use "" because it will be colored distinctively yellow in my code... for some reason String.Empty is all white in my Visual Studio Code theme. And I believe that matters to me the most.

5argon
  • 3,683
  • 3
  • 31
  • 57
1

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
  • 577
  • 6
  • 10
1

The empty string is like empty set just a name that everybody uses to call "". Also in formal languages strings created from an alphabet that have zero length are called the empty string. Both set and string have a special symbol for it. Empty string: ε and empty set: ∅. If you want to talk about this zero length string you will call it the empty string so everybody knows exactly what you are referring to. Now in case you name it the empty string why not use string.Empty in code, its shows the intention is explicit. Downside is that it’s not a constant and therefore not available everywhere, like in attributes. (It's not a constant for some technical reasons, see the reference source.)

Wouter
  • 2,540
  • 19
  • 31
1

On http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx :

As David implies, there difference between String.Empty and "" are pretty small, but there is a difference. "" actually creates an object, it will likely be pulled out of the string intern pool, but still... while String.Empty creates no object... so if you are really looking for ultimately in memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your code...
As for System.String.Empty or string.Empty or String.Empty... my care level is low ;-)

Otiel
  • 18,404
  • 16
  • 78
  • 126
sergiol
  • 4,122
  • 4
  • 47
  • 81
  • 2
    That MSDN blog post was in 2003.... are you sure that this is still true for recent .NET versions?! – Carsten Schütte Apr 28 '13 at 20:45
  • @CarstenSchütte: Seems to me that such a feature is not intended to change very much ... and if it was, there was some buzz on the Internet about it. – sergiol Apr 29 '13 at 12:03
  • 3
    @sergiol If a field is more efficient than a literal then this is unambiguously a performance bug. So there’s hoping that it would be fixed by now. – Konrad Rudolph Jan 26 '16 at 11:41
0

Possibly a controversial comment, but, generally, I find that my life is easier when I act consistently with Microsoft. We can't possibly know the full deeply embedded reasons (sometimes highly rigorous, and sometime kludgy, I imagine) for why they do things.

They use "" in automatically generated files like the Assembly file, so that is what I do. In fact, when I try to replace any below "" with String.Empty, Visual Studio crashes on me. There is probably a logical explanation for this, but with my limited knowledge, if I just do what they do, most of the time, things work out. (Contra: I am aware they some automatically generated files also use String.Empty, which kind of shatters my point. :) )

<Assembly: System.Reflection.AssemblyCulture("")>
<Assembly: System.Reflection.AssemblyDescription("")>
<Assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")>
<Assembly: System.Reflection.AssemblyKeyFile("")>
<Assembly: System.Reflection.AssemblyProduct("")>
<Assembly: System.Reflection.AssemblyTitle("")>
Keith Howard
  • 347
  • 4
  • 12
  • Expand your knowledge by reading the other answers and by taking your time to actually understand them. :-) Maintaining consistency with the rest of your codebase and with other codebases (.NET itself, generated code...) is a good rule of thumb, but it is not always clearly applicable and sometimes even harmful -- e.g. you need to do something very specific or you are the first one to spot a deficiency in current practices on the team. Moreover, consistency with something you don't understand may lead to [cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming). – Palec Dec 29 '21 at 19:14