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
Some coders will wrap each condition in its own parentheses, like this:
Style #1:
bool Test(string a, string b)
{
return ((a != null) && (b != null));
}
Style #2:
bool Test(string a, string b)
{
return a != null && b != null;
}
In C# the difference is purely stylistic (at least, I think so). The first expression evaluates first, and the second expression evaluates only if the first is true (otherwise it short-circuits because the entire expression is already confirmed false).
Someone mentioned that #1 above is an "old C style". What is its practical purpose? Is there any actual difference between the two, or is it some kind of safeguard against typos (like writing if (true == x) instead of if (x == true)).
I think this is just defensive coding so the writer of the code (and more importantly, future readers) do not have any doubts about the intent and function of the code.
A long time ago I spent many tedious evenings working through code with a colleague who refused to bracket terms due to his unfailing belief in his ability to remember precedence rules. Despite many examples to the contrary. Even when you know those rules yourself it is easier to read code where the intent is crystal clear, rather than double-checking every time.
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 1 year ago.
Improve this question
A colleague told me I could use is and is not instead of the equality operators == and !=. I thought the is operator had something to do with types, and the official docs on MSDN agrees, but it also states:
Beginning with C# 7.0, you can also use the is operator to match an expression against a pattern
I didn't think checking values with is would work, but strangely it does:
> "tomato" is "apple"
false
> 1 is not 2
true
I assume it is the "expression pattern matching" at work here(?). My question is, since using is as the equality operator (==) seemingly works for values as well, is there any reason to avoid it? Would it be fine, performance and readability wise, to use is for all equality checks?
With the exception of x is null they are the same and a matter of taste for constant values. As in described in the comments, pattern matching only works for constants. The special case of checking for null guarantees to not use any overloaded equality operator. I cross-checked that with ILSpy:
Original source code:
string tomatoString = "tomato";
object tomatoObj = "tomato";
Console.WriteLine(tomatoString.Equals("tomato"));
Console.WriteLine(tomatoString is "tomato");
Console.WriteLine(tomatoObj is "tomato");
Console.WriteLine("tomato" is "tomato");
Console.WriteLine(tomatoString is null);
Decompiled with ILSpy:
string tomatoString = "tomato";
object tomatoObj = "tomato";
Console.WriteLine(tomatoString.Equals("tomato"));
Console.WriteLine(tomatoString == "tomato");
string text = tomatoObj as string;
Console.WriteLine(text != null && text == "tomato");
Console.WriteLine(value: true);
Console.WriteLine(tomatoString == null);
(For Completness: Note that if you test it with literals on both sides, the compiler will just replace it with its constant result. Note that the static type will introduce necessary null checks)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to compare two strings in a linq expression. Do I take advantage if I use `string.CompareOrdinal or is it the same?
list.Where(str1 => string.CompareOrdinal(str1, str2) == 0);
list.Where(str1 => str1 == str2);
According to benchmarks done by someone else, string.CompareOrdinal can be slightly faster than == when doing a lot of comparisons:
Most of the board remained green up through 10,000 comparisons and didn’t register any time.
At the 100,000 and 1,000,000 marks, things started to get a bit more interesting in terms of time differences.
String.CompareOrdinal was the constant superstar. What surprised me is for the case-insensitive comparisons, String.CompareOrdinal outperformed most other methods by a whole decimal place.
For case sensitive comparisons, most programmers can probably stick with the “==” operator.
-- The Curious Consultant: Fastest Way to Compare Strings in C# .Net
Note, though, that we are talking about a total difference of 3 milliseconds for 100,000 case-sensitive string comparisons, and that no measurable differences have been observed for 10,000 and 1,000,000 comparisons.
Thus, is very unlikely that this difference is relevant to your application (especially if you are using LINQ-to-objects), so the more readable == should be preferred.
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 6 years ago.
Improve this question
I know "goes to" has been suggested in MSDN. I also know it is not a universal usage and also creates confusion to many.
Since basically:
x => x + 1
Is equivalent to:
delegate (int x) { return x + 1; }
I think the use of the word "return" while reading is paramount to clear what the lambda expression does to everyone.
Is it much better than "goes to" or even worst for some lambda expression uses I am not aware?
For what its worth, => was always "such that" to me.
The one issue with saying "returns" is that a lambda, as the shorthand form for any anonymous method, does not always return a value. Lambdas are perfectly valid values for Action<T> variables for example.
I would probably stick with something more generic like "goes to" or "such that" but if it helps you understand then use what works for you.
In my opinion, "return" is a really bad naming for this. It might be kind of ok in your case, but in general the return has nothing to do with the expression you gave. It is just syntactical sugar that when you only have one statement you can write it without the curly brackets and the statement gets returned anyway.
To make my point clear, consider the following:
someList.ForEach(x =>
{
Console.WriteLine(x);
}
There is no return or anything similar. I think the term "goes to" describes it way better. If I had to come up with some term, i would probably use "do". Meaning ForEach x do Console.WriteLine or in your case for x => x + 1 it will translate into x do x + 1.
Anyway, this is just a personal thought of mine.
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 6 years ago.
Improve this question
Today I was working on a TextToSpeech app and I've came across a situation where I need to check if the selected voice by the user is installed on the computer.
For this, I could either use a foreach:
bool foundVoice = false;
foreach (var v in installedVoices)
{
if (v.VoiceInfo.Name.Contains(selectedVoice) && v.VoiceInfo.Culture.ToString() == selectedCulture)
{
foundVoice = true;
break;
}
}
Or a lamda expression:
var foundVoice = installedVoices.FirstOrDefault(v => v.VoiceInfo.Name.Contains(selectedVoice) && v.VoiceInfo.Culture.ToString() == selectedCulture);
The installedVoices is a ReadOnlyCollection< InstalledVoice > from SpeechSynthesizer.
Definitely, the lambda expression looks more cleaner than the foreach but which one is better practice?
From what I have tested the foreach seems to be slightly faster than the lambda expression.
Also, both foreach and lambda can be extended in the future if there is need for immediate action on the InstalledVoice.
the lambda expression looks more cleaner than the foreach but which one is better practice?
"Looks cleaner" is a perfect indicator of a better practice. It is extremely rare for performance to change in a meaningful way depending on the language facility in use, so readability is the most important measure of how good a particular construct is for your code. Readability is what ultimately decides the maintainability of your code, even when the only reader of your code is you.
Note that this is a case-by-case decision, because lambdas may be better in one situation and loops could be better in another situation.
Yes, it's good practice to use LINQ in this case, because it's more readable. However, to me installedVoices.Any instead of installedVoices.FirstOrDefault would be even more readable.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm returning a string from an API that has a length of 45 characters. There is one word that is unique for one condition that doesn't appear in the other condition.
I'm wondering if using string.contains() is faster performance-wise than comparing the whole string with string.equals() or string == "blah blah".
I don't know the inner workings of any of these methods, but logically, it seems like contains() should be faster because it can stop traversing the string after it finds the match. Is this accurate? Incidentally, the word I want to check is the first word in the string.
I agree with D Stanley (comment). You should use String.StartsWith()
That said, I also don't know the inner working of each method either, but I can see your logic. However "String.Contains()" may still load the entire string before processing it, in which case the performance difference would be very small.
As a final point, with a string length of only 45 characters, the performance difference should me extremely minute. I was shocked when I wrote a junky method to substitute characters and found that is processes ~10kb of text in a fraction of a blink of the eye. So unless you're doing some crazy handling else wise in your app, it shouldn't matter much.