This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between String.Empty and “”
Why it is recommended to use string.Empty instead of ""? From one side, I understand, that it makes code clearer, without "Magic constants". Is there any another technical benefits of using string.Empty?
Thanks.
Per Brad Abrams blog:
the 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…
It's pretty insignificant.
I believe this has been answered before, but to summarize: preference and readability.
They are completely equivalent, and are up to whatever you and your fellow developers prefer, just be consistent. :)
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Edit: I changed most of my question, because it was too long and altough my question is a request of facts, it was considered opinion based. Having said that, please read the comments where I try to explain why closing this question was wrong IMHO.
Also: I'd like to appologize for my initial question, I am not a native English speaker and I didn't know the word [blindly] had such a negative tone. I actually used the word in other questions.
Background:
Consider the following piece of C# code:
for(; /*empty condition*/ ;)
{
//Infinite loop
}
This amongst other methods is considered good practice to make an infinite loop. But when we would try a similar approach with a while loop it would never compile:
while(/*empty condition*/)
{
//Compiler error
}
At first I thought that this was some sort of bug in my compiler, but then I read the C# language specification. I found this was be design. Why? Because C# is based on C, and C behaves this way.
So now the question is, why does C behave like this? Somebody else asked this question on StackOverflow already. The answer was pretty unsatisfying and came down to this:
It behaves like this because it is described like this in the C language specification.
This answer reminded me of many discussions I had with my parents when I was a kid: "Why do I have to clean my room?" - "Because we say so.". Further answers speculate (i.e. no sources or arguments were added) that while() is "hacky" and that "using for(;;) made more sense".
My research
Edit: deleted because it was considered to long. It basically was an effort to figure out why C had this construction.
My question:
After all my research I concluded that the while loop's inability to accept empty expressions is illogical if the for loop can.
But if that is true, then why did the C# language design team copy this bevahiour?
You: "C# is based on C and why would you reinvent the wheel?"
True, but why make the same illogical decissions? If your grandfather would jump of a bridge, then would you do it too, just because you are based on him? And isn't the creation of a new language - based on an old one - the ideal situation to avoid/fix the illogical pitfalls of the old language?
So to repeat my question:
Why did the C# design team copy this behaviour?
After all my research I can only conclude that the while loop's inability to accept empty expressions is illogical.
A very far fetched conclusion. IMHO it is the for(;;) loop that is illogical (and not only in this respect).
It is clear that while() { ... } would have been possible but what exactly is the merit?
As a matter of style I would prefer for(;true;) over for(;;), it has less chance of being misread.
Being able to write a 'for-ever' loop is a minor issue, avoiding typos is much more important.
Readability is the only thing that counts, you're not making much of a case for while().
And what should happen in this statement?
if() Foo();
C11 specification states:
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the
controlling expression that is evaluated before each execution of the
loop body. The expression expression-3 is evaluated as a void
expression after each execution of the loop body. If clause-1 is a
declaration, the scope of any identifiers it declares is the remainder
of the declaration and the entire loop, including the other two
expressions; it is reached in the order of execution before the first
evaluation of the controlling expression. If clause-1 is an
expression, it is evaluated as a void expression before the first
evaluation of the controlling expression. 158)
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a
nonzero constant.
which is not the case with the while-loop. However this is C11. ANSI C doesn't make this clear really. Though, I assume C# is based on how C most commonly work(s|ed), not how it's specified to work.
To speculate, I could think that the for-loop in early C wasn't well defined, so programmers found out that you can write an infinite loop like for (;;). To be compatible with old programs, the standards never forbid this. So there is really no reason to write like this. It's just history I guess.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I using c# winforms and wanted to know how it's better to write and why.
if(txtName.Text == "John")
;
or
String name = txtName.Text
if (name == "John")
;
Edit: Thanks guys you helped me a lot!!!
The second version is pointless - it is longer, less readable and introduces one extra variable (though a good compiler would get rid of it, assuming it is not used elsewhere).
Of the two choices, this one is better:
if(txtName.Text == "John")
Though I would go with a third:
if(txtName.Text.Equals("John", StringComparison.InvariantCultureIgnoreCase)
You may want the StringComparison option to be a different enumeration value, depending on how you want the comparison to occur.
For simplicity sake I would go with:
if(txtName.Text.Equals("John"))
Maybe I'm wrong, but others are answering to some complex scenario which isn't the case of one suggested by OP.
What's better?
In fact, it's the same. There's a single difference: first approach, you're storing control's text in a variable and later you check if it's equal to John. Second approach does the same thing, but it gets control's text accessing its string value directly by calling Text property.
When to use a variable and when to access to the property directly? It's just an assumption, because this will depend on each particular use case, but in common terms, call Text property directly if you're accessing its object (the text) just for checking it in a moment of time, otherwise, you'd want to store it in some variable if:
If you want to do some concatenation with Text without affecting the text held by this (if you concatenate it to the Text, you're going to modify it in your app user interface too!).
You're in a multi-threaded environment and you want to get Text in its current state because it can change since user interface is available to the user and it can change its value during some operation.
You just like variables!. If you find using variables clarifies your code better and adds meaning, why not? Nowadays' computers, even mobile phones, have a lot of memory and one, two or three variables wouldn't change anything (maybe 1KB more? wohoo!).
That's all.
Read Best Practices for Using Strings in the .NET Framework.
if (String.Equals(txtName.Text, "John", StringComparison.OrdinalIgnoreCase)) {
// ...Code.
}
For string comparison i would suggest:
string.compare(strA, strB, stringComparisonMethod)
For accessing the text it doesn't matter, the second way is more friendly but both will do the same
I think the later is better because you will be using a less variable i.e. name . Except that I don't see any difference (the styling is obviously upto yourself)
If you're using the value in other parts of your code, I'd go with defining a variable. Otherwise, use the shorter version.
In C# you don't have to use .Equals to compare strings (in response to a comment). == does the same thing.
if(txtName.Text == "John")
This is more conventional and efficient way of these you have shown.
String name = txtName.Text
if (name == "John")
;
Declaring extra variable "name" will increase the code size with any benefit except increasing the program memory. Once I tried and found declaring extra variable and assigning text to it and later accessing this variable instead of text property txtName.Text makes it less efficient then accessing through property.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why is String.Concat not optimized to StringBuilder.Append?
One day I was ranting about a particular Telerik control to a friend of mine. I told him that it took several seconds to generate a controls tree, and after profiling I found out that it is using a string concatenation in a loop instead of a StringBuilder. After rewriting it worked almost instantaneously.
So my friend heard that and seemed to be surprised that the C# compiler didn't do that conversion automatically like the Java compiler does. Reading many of Eric Lippert's answers I realize that this feature didn't make it because it wasn't deemed worthy enough. But if, hypothetically, costs were small to implement it, what rationale would stop one from doing it?
But if, hypothetically, costs were small to implement it, what rationale would stop one from doing it?
It sounds like you're proposing a bit of a tautology: if there is no reason to not do X, then is there a reason to not do X? No.
I see little value in knowing the answers to hypothetical, counterfactual questions. Perhaps a better question to ask would be a question about the real world:
Are there programming languages that use this optimization?
Yes. In JScript.NET, we detect string concatenations in loops and the compiler turns them into calls to a string builder.
That might then be followed up with:
What are some of the differences between JScript .NET and C# that justify the optimization in the one language but not in the other?
A core assumption of JScript.NET is that its programmers are mostly going to be JavaScript programmers, and many of them will have already built libraries that must run in any implementation of ECMAScript. Those programmers might not know the .NET framework well, and even if they do, they might not be able to use StringBuilder without making their library code non-portable. It is also reasonable to assume that JavaScript programmers may be either novice programmers, or programmers who came to programming via their line of business rather than a course of study in computer science.
C# programmers are far more likely to know the .NET framework well, to write libraries that work with the framework, and to be experienced programmers who understand why looped string concatenation is O(n2) in the naive implementation. They need this optimization generated by the compiler less because they can just do it themselves if they deem it necessary.
In short: compiler features are about spending our budget to add value for the customer; you get more "bang for buck" adding the feature to JScript.NET than you do adding it to C#.
The C# compiler does better than that.
a + b + c is compiled to String.Concat(a, b, c), which is faster than StringBuilder.
"a" + "b" is compiled directly to "ab" (useful for multi-line literals).
The only place to use StringBuilder is when concatenating repetitively inside a loop; the compiler cannot easily optimize that.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the difference between String.Empty and “”
Hello
Simple Question;
Why
Textbox1.Text = String.Empty;
is better than
Textbox1.Text = "";
?
It's not, really.
Basically, decide which you find to be more readable. Personally I use "" instead of string.Empty, but others prefer the latter.
Back in .NET 1.x days apparently there was some tiny performance difference (almost certainly irrelevant in real apps) but I believe these days even that's gone.
Use whichever you and your find most readable.
Because String.Empty is actually defined as ""
Best practices dictate not to use string literals but constants.
On a funnier note: String.Empty is/looks more Object Oriented-ISH.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
In C#, should I use string.Empty or String.Empty or “” ?
Is there any difference in c# between the following declarations...
private string m_port = string.Empty;
or...
private string m_port = "";
Is it just coding standard that makes it look neater?
Just coding standard...
http://msdn.microsoft.com/en-US/library/system.string.empty%28VS.80%29.aspx
They are the same, but looks better.
The main difference is one of semantics - string.Emtpy says that you meant to have an empty string. "" might be a mistake (" ", for instance).
Since String.Empty is an instance it should remove the overhead of the object creation, however I think a parser should be smart enough to figure this out.
All string literals is also pulled from an object pool I believe, so the object creation might not even take place.