String Comparison set to boolean variable - c#

I assume this should be fine
bool prefMatch = false;
// Is the frequency the same?
prefMatch = string.Compare(user.Frequency, pref.Action.ToString()) == 0;
so if user.Frequency is "3" and pref.Action.ToString() is "3" then it should set the prefMatch to true right? I'm getting false and I've definitely checked the 2 values in the watch tab in VS 2008 just to be sure they're the same

You can just use ==
prefMath = (user.Frequency == pref.Action.ToString());
Though string.Compare will also work. I suggest there is a problem elsewhere.
-- Edit
Also, just for completeness, there is no point assigning a variable to something, and then assigning it again directly after. It's slightly confusing to do so, so better to leave it unassigned, or assign it all in one spot. This way the compiler can help you if you have a case where it doesn't get assigned like you think. It is, obviously, acceptable to assign first if you wrap the second assignment in a try/catch though.

In situations like these, it's sometimes tempting to point the finger of blame at third-party code, as you've done here. Sometimes, this is justified - but not here. String.Compare is a central, extremely-well-tested piece of the .NET Framework. It's not failing. I guarantee it.
What I find helpful in these situations is to isolate the failure. Write a small, self-contained test case that attempts to demonstrate the problem. Write it with as few dependencies as possible. Make it a stand-alone console application, if possible. Post it here. If we can take it, compile and run it, and reproduce the problem, we can help you. I'd bet money, though, that in the course of creating this test case, you'll experience a head-slapping moment - "of course!" - and realize what the problem is.

Maybe the string(s) contain unprintable characters ?
To check, I'd do something like :
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(user.Frequency);
byte[] b2 = System.Text.Encoding.UTF8.GetBytes(pref.Action.ToString());
then compare the contents of b1 and b2.

Related

Combine multiple lines of C# code for brevity or separate for clarity

I am fairly new to c# and trying to learn best practices. I've been faced with many situations over the last week in which I need to make a choice between longer+simpler code, or shorter code that combines several actions into a single statement. What are some standards you veteran coders use when trying to write clear, concise code? Here is an example of code I'm writing with two options. Which is preferable?
A)
if (ncPointType.StartsWith("A"))//analog points
{
string[] precisionString = Regex.Split(unitsParam.Last(), ", ");
precision = int.Parse(precisionString[1]);
}
else
precision = null;
B)
if (ncPointType.StartsWith("A"))//analog points
precision = int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]);
else
precision = null;
There is no right or wrong. This is opinion based really.
However, remember that whether you add braces, add comments, add whitespace or whatever, it doesn't affect the performance or the size of the final assembly because the compiler optimizes it very well. So, why not go with the more verbose so that other programmers can follow it easier?
This is basically subject to the coding standard you choose. There is no right or wrong, just personal preference.
Agree as a team what you prefer.
But even better is:
precision = ncPointType.StartsWith("A")?
int.Parse(Regex.Split(unitsParam.Last(), ", ")):
null;
This expresses the function beiong executed (set the precision),
and the conditions that control how it is set, in even less code,
- without creating unnecessary temporary variables to hold a temporary result that is not used anywhere else.
If you ask me both A and B are bad practice. You should always use braces regardless of whether or not it is one line or multiple lines. This helps to prevent bugs in the future when people add additional lines of code to your if or else blocks and don't notice that the braces are missing.
Sometimes having "more" code, like using temporary variables, etc., will make your code easier to debug as you can hover over symbols. It's all about balance, and this comes with experience. Remember that you may not be the only one working on your code, so clarity above all.
Ultimately it comes down to your choice because it has nothing to do with performance, but I would also note that you cannot instantiate or define variables if you omit the curly braces:
int a = 0;
if (a == 0)
int b = 3;
Is not valid, whereas:
int a = 0;
if (a == 0)
{
int b = 3;
}
Is valid.
It's easier to debug option A, but option B is more concise while still being readable. You could make it even more concise with a ternary operator:
precision = ncPointType.StartsWith("A") ? int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]) : null;
Although it's far more readable this way (and still works the same way!):
precision = ncPointType.StartsWith("A") ?
int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]) :
null;
It's best to stick with the standards used in your project. Readability is far more important for maintainability than having less lines of code. In both options, the efficiency is the same, so you don't need to worry about speed in this case.
As everyone else here points out, there are no hard and fast "rules" per se, but there should probably be braces around both block of code; both A and B have characteristics similar to the Apple goto bug because the introduce potential ambiguity.
Consider:
void Main()
{
int x=1;
if (x==1)
Console.WriteLine("1");
else if (x==2)
Console.WriteLine("NOT 1");
Console.WriteLine("OK");
}
will produce
1
OK
To someone scanning the code, especially if it's surrounded by other, innocuous looking code, this could easily be misread as "only print "OK" if x==2). Obviously some people will spot it, some won't, but why introduce the danger for the want of a brace of braces :)

Acceptable to have spaces before dot?

What is the general opinion on the 2nd indentation method below.
// Normal indentation
a.Value = "foobar";
ab.Checked = false;
foo.Value = "foobar";
foobar.Checked = true;
// Spaces before the dot to align the properties/methods
a .Value = "foobar";
ab .Checked = false;
foo .Value = "foobar";
foobar.Checked = true;
This should probably be a wiki, but I either don't have enough privileges or don't know how to change it.
edit
I've decided to add another example to better show where such an indentation style might be useful.
fooA .PropertyA = true;
foobarB.PropertyA = true;
Changing PropertyA on all lines would be much easier with the new multi-line editing feature in VS2010.
Also having whitespace, and even line-breaks before the dot is not uncommon at all in C# (see LINQ).
Spaces before the dot? Dear God no!
I would never use either personally. I would use just traditional formatting, eg:
a.Value = "foobar";
ab.Checked = false;
foo.Value = "foobar";
foobar.Checked = true;
I understand this may not be as pleasing to the eye, but feel the others are less ideal.
Reasons being:-
Harder to maintain: Sometimes you may have smaller or larger variable names, or introduce other variables in your code which means you have to adjust formatting of all entries.
Automatic formatting might mess this up: If you use ReSharper (possibly with standard VS?) when pressing ; the formatting will adjust it back into line anyway, so you have to go out of your way to ensure it wouldn't do this.
I can't think of one right now, but I can't handle only having two points.
Edit! Thought of another point. There are more tricky keystrokes involved: For instance, for me with ReSharper to achieve the latter formatting I would type foo, enter/tab (to confirm auto-complete), tab times X amount of tabs required up to variable length (annoying), ., Value, tab to confirm auto-complete again, = then assigning data then ; and then yell at Visual Studio because all my non-standard formatting was undone as I expressed in point 2, so finally a press of CTRL+z would restore back the formatting we just had. :)
I've always used "Normal indentation." The other way seems less clear to me because I am not expecting to see indentation of that nature.
I would use spaces before the dot only if it's all the same property/method. If it's a mix of properties, like you have in your example, I'd stick with 'Normal'.
However, I think it's a moot point, because the Visual Studio autoformatter will collapse everything next time someone types a } to close any enclosing block.
Acceptable from C# language point of view.
First style is easier for me to read compared to second. I think it is because spaces before dot look very strange - in most written languages there is no space before dot.
I personally don't fight with VS IDE. Default style is fine with me.
Note that using proportional fonts totally breaks such formatting (using such fonts is extremly unusual for editing code, but ask around).
Edit: using space (+new line) for fluent interfaces looks good ( http://en.wikipedia.org/wiki/Fluent_interface#C.23).
I tried it a couple of time. Never was happy with out it looked afterwords.
I always thought aligning on the 'dot' might work in the right context:
// -----------------------
// decimal-style alignment
// -----------------------
a.Value = "foobar" ;
ab.Checked = false ;
foo.Value = "foobar" ;
foobar.Checked = true ;
But you lose the clean left margin that leads the eye down the page and maintains your sense of indent level. So you're back to keeping the dot with the identifiers it connects. However...
Aligning the equal signs is good practice as it helps order the whole set:
// -----------------------
// tabular coding
// -----------------------
a.Value = "foobar" ;
ab.Checked = false ;
foo.Value = "foobar" ;
foobar.Checked = true ;
The more order one imposes on one's code the more likely one is to notice things that are out of whack.
The parser doesn't care about tidy, readable code, but the compiler isn't the target audience for your code. Your target audience is other human beings that have to read it and comprehend it. In particular the poor schmuck — who might be you! — that has to pick up the code in a hurry and fix it 3 or 5 years from now, without no documentation to aid in understanding.
The spaces before the dots I would NEVER do, simply because as I am reading code I stop looking for a dot as soon as I see a space. The spaces after the dot, I HAVE done in the past, but hardly ever and I really prefer not to use it. The problem with using a style like that is that even if it is more readable to you, if you take such a large leap (meaning the spaces before the dot) from what might be considered a "norm" then you are going to hinder more people than help. Sticking with the standard in your team or workplace is the most important thing. Even if it is not a black and white standard, if the other 99 developers at your company us VS standard and you put all the spacing before your dots it is not going to improve anything.

Is there any plugin for VS or program to show type and value etc... of a C# code selection?

What I want to do is be told the type, value (if there is one at compile-time) and other information (I do not know what I need now) of a selection of an expression.
For example, if I have an expression like
int i = unchecked((short)0xFF);
selecting 0xFF will give me (Int32, 255), while selecting ((short)0xFF) will give me (Int16, 255), and selecting i will give me (Int32, 255).
Reason why I want such a feature is to be able to verify my assumptions. It's pretty easy to assume that 0xFF is a byte but it is actually an int. I could of course refer to the C# Language Specifications all the time, but I think it's inefficient to have to refer to it everytime I want to check something out. I could also use something like ANTLR but the learning curve is high.
I do intend to read the entire specs and learn ANTLR and about compilers, but that's for later. Right now I wish to have tools to help me get the job done quickly and accurately.
Another case in point:
int? i = 0x10;
int? j = null;
int x;
x = (i >> 4) ?? -1;//x=1
x = (j >> 4) ?? -1;//x=-1
It may seem easy to you or even natural for the bottom two lines in the code above. (Maybe one should avoid code like these, but that's another story) However, what msdn says about the null-coalescing operator is lacking information to tell me that the above code ((i>>4)??) is legal (yet it is, and it is). I had to dig into grammar in the specs to know what's happening:
null-coalescing-expression
conditional-or-expression
conditional-and-expression
exclusive-or-expression
and-expression
equality-expression
relational-expression
shift-expression
shift-expression right-shift additive-expression
... (and more)
Only after reading so much can I get a satisfactory confirmation that it is valid code and does what I think it does. There should be a much simpler way for the average programmer to verify (not about validity, but whether it behaves as thought or not, and also to satisfy my curiosity) such code without having to dive into that canonical manual. It doesn't necessary have to be a VS plugin. Any alternative that is intuitive to use will do just as well.
Well, I'm not aware of any add-ins that do what you describe - however, there is a trick you can use figure out the type of an expression (but not the compile-time value):
Assign the expression to a var variable, and hover your mouse over the keyword var.
So for example, when you write:
var i = unchecked((short)0xFF);
and then hover your mouse over the keyword var, you get a tooltip that says something like:
Struct System.Int16
Represents a 16-bit signed integer.
This is definitely a bit awkward - since you have to potentially change code to make it work. But in a pinch, it let's you get the compiler to figure out the type of an expression for you.
Keep in mind, this approach doesn't really help you once you start throwing casts into the picture. For instance:
object a = 0xFF;
var z = (string)a; // compiles but fails at runtime!
In the example above, the IDE will dutifully report that the type of var z is System.String - but this is, of course, entirely wrong.
Your question is a little vague on what you are looking for, so I don't know if "improved" intellisense solves it, but I would try the Productivity Power Tools.

c# string performance - what is faster to compare, string text or string length

I have to read a huge xml file which consists of over 3 million records and over 10 million nested elements.
Naturally I am using xmltextreader and have got my parsing time down to about 40 seconds from earlier 90 seconds using multiple optimization tricks and tips.
But I want to further save processing time as much as I can hence below question.
Quite a few elements are of type xs:boolean and the data provider always represents values as "true" or "false" - never "1" or "0".
For such cases my earliest code was:
if (xmlTextReader.Value == "true")
{
bool subtitled = true;
}
which i further optimized to:
if (string.Equals(xmlTextReader.Value, "true", StringComparison.OrdinalIgnoreCase))
{
bool subtitled = true;
}
I wanted to know if below would be fastest (because its either "true" or "false")?
if (xtr.value.length == 4)
{
bool subtitled = true;
}
Yes, it is faster, because you only compare exactly one value, namely the length of the string.
By comparing two strings with each other, you compare each and every character, as long as both characters are the same. So if you're finding a match for the string "true", you're going to do 4 comparisons before the predicate evaluates to true.
The only problem you have with this solution is, that if someday the value is going to change from true to let's say 1, you're going to run into a problem here.
Comparing length will be faster, but less readable. I wouldn't use it unless I profile the performance of the code and conclude that I need this optimization.
What about comparing the first character to "t"?
Should (maybe :) be faster than comparing the whole string..
Measuring the length would almost invariably be faster. That said, unless this is an experiment in micro-optimization, I'd just focus on making the code to be readable and convey the proper semantics.
You might also try something like that uses the following approach:
Boolean.TryParse(xmlTextReader.Value, out subtitled)
I know that has nothing to do with your question, but I figured I'd throw it out there anyway.
Cant you just write a unit test? Run each scenario for example 1000 times and compare the datetimes.
If you know it's either "true" or "false", the last snippet must be fastest.
Anyway, you can also write:
bool subtitled = (xtr.Value.length == 4);
That should be even faster.
Old question I know but the accepted answer is wrong, or at least, incorrect in it's explanation.
Comparing the lengths maybe be the slightest bit faster but only because string.Equals is likely doing some other comparisons before it too checks the lengths and decides that they are not equal strings.
So in practice this is an optimization of last resort.
Here you can find the source for .NET core string comparison.
String comparing and parsing is very slow in .Net, I'd recommend avoid intensive using string parsing/comparing in .Net.
If you're forced to do it -- use highly optimized unmanaged or unsafe code and use parallelism.
IMHO.

What is the way to apply extension methods?

When attempting to solve the problem
How many seven-element subsets (not repeatable) are there in a set of nine elements ?
I tried
IEnumerable<string> NineSet =new string[] {"a","b","c","d","e","f","g","h","i"};
var SevenSet =
from first in NineSet
from second in NineSet
where first.CompareTo(second)< 0 && first.Count() + second.Count()==7
select new { first, second };
What is the problem that prevents me from attempting to use first.Count() and second.Count()? I did not check whether it is the best solution for the problem.
As already stated, what you have written down will lead you to nowhere. This is a question of combinatorics. AFAIK there is nothing pre-made in the .NET framework to solve for you combinatorics problems, hence you will have to implement the correct algorithm. If you get stuck, there are solutions out there, e.g. http://www.codeproject.com/KB/recipes/Combinatorics.aspx, where you can look at the source to see what you need to do.
first and second are strings, so you'll count their characters (this compiles, but intellisence hides it).
You're looking for something like NineSet.Count(first.Equals)
Well...
You haven't shown the error message, so it's hard to know what's wrong
Every element is of length exactly one, so I'm not sure what you're expecting to happen
As you know that first and second are strings, why aren't you using first.Length and second.Length?
As a side issue, I don't think this approach is going to solve the problem for you, I'm afraid...

Categories

Resources