Difference between Forward and Reverse Comparison in C# - c#

this is related to comparing values in C#.
basically by default, in C# till date i only used forward comparison as follows:
string value1 = "";
if (value1 == null)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
somewhere on Internet, i came across a link where it is said that while comparing values in C#, we should prefer Reverse Comparison as :
string value1 = "";
if (null == value1)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Now the problem is that is there any basic difference between the two ways of comparing values or not (i.e. both are same).
Looking for favorable replies.
Thanks

This is a hangover from languages where values are implicitly converted to a boolean type.
For the most part, anything that was non-null or non-0 would be treated as true, otherwise it was equivalent to false. This meant that any assignation of a constant would always be true.
This thing to remember here is that the assignment function returns the value assigned, much in the same way that 5 is the result of 2+3, myInt = 5 also returns 5.
Because of this, it was recommended that you check the variable against the constant. The null example is actually probably a bit contrived in this case, as it would, in most languages, return as false.
As an example:
if(i = 1)
{
printf("Always out\n");
}
else
{
printf("Never prints\n");
}
i is assigned the value of 1, which then returns the value of the assignment, 1, to the if statement. This is equivalent to true, and the if condition matches.
If you were to attempt to assign i to the constant 1, you wouldn't compile, and so it was recommended that you do things it that order (e.g. 1 == i).
This is not neccesary in C#, and further to your example, the recommended practice is to call if(String.IsNullOrEmpty(myStringValue)) { //.... }, as a string has... two ... default values from a semantic perspective.

Reverse comparison protects you from errors, when you use == (compare) instead of = (assign). But complier also warns you if you do this.

Related

Nullable vs. Out Parameter when checking for valid/existent values

I have two questions and I'd like some help with them, please.
I have client code that needs to access to a variable/value that is changing over time, in fact, it is calculated on retrieval, and it is retrieved by many methods several times over runtime, however, it's calculation is not always possible as the requirements for it are not always present, in such cases, a false or null is returned and the client checks this to decide wether to proceed. Now, I have two approaches, the first one, A, is my classic one, B however, looks good to me as well.
A) I have this method with an out parameter similar to the TryParse methods on some C# libraries:
public bool GetLeadingTrailSegment(out Vector3 lastTrailSegment)
{
if (_line.positionCount > 1)
{
lastTrailSegment = lead - _line.GetPosition(_line.positionCount - 2);
return true;
}
lastTrailSegment = Vector3.zero;
return false;
}
B) I have this nullable property which tries to do the same job as the above code:
public Vector3? leadingTrailSegment
{
get
{
if (_line.positionCount > 1)
{
return lead - _line.GetPosition(_line.positionCount - 2);
}
return null;
}
}
The client code is as follows:
A) Here the bool tells the client code wether the value is safe(useful?) to use.
public bool IsDrawingOverAllowed(LayoutPointer pointer)
{
Vector3 leadingTrailSegment;
if (pointer.GetLeadingTrailSegment(out leadingTrailSegment))
{
return !midline.ParallelTo(leadingTrailSegment);
}
return true;
}
B) Here, the fact of the HasValue property of the nullable being false tells the client wether it is safe:
public bool IsDrawingOverAllowed(LayoutPointer pointer)
{
Vector3? leadingTrailSegment = pointer.leadingTrailSegment;
if (leadingTrailSegment.HasValue)
{
return !midline.ParallelTo(leadingTrailSegment.Value);
}
return true;
}
First question: Of these two approaches, which one is best or what are the pros/cons between or flaws within them?
Second question: I used to have the client B approach written as:
public bool IsDrawingOverAllowed(LayoutPointer pointer)
{
if (pointer.leadingTrailSegment.HasValue)
{
return !midline.ParallelTo(pointer.leadingTrailSegment.Value);
}
return true;
}
This was wrong, right? Because the Value property of the nullable may have changed by the second call.
I like best the out parameter approach, you can use the result in the if clause, and the variable can even be declared inline in other versions of C# but I'd really like to give a shot to nullables and make them useful in situations like these (and not only when I look for an unassigned value, which are the cases I use them in). I hope someone can give their thoughts on this.
Thanks.
I would much prefer a call returning a null than using output parameters. Output parameters are a kind of "side-effect" prone code constructs that I personally really dislike. It means the calling code has to define a variable before use, and it introduces weak points where it would be easy to induce a bug if you put in the wrong variable in the call by accident. It also prevents you from using the code in a call chain with the null-conditional and null-coalescing operators. You cannot do something like var v = GetLeadingTrailSegment() ?? new Vector3();.
The second point of interest is the use of a Nullable. If the Vector3 type is a value type, then that is fine and makes sense. If it is a reference type (pretty much everything other than integral types and structures in .NET), there is no need for it. Just return null; and if (variable != null) { ... }. The case for returning a bool is usually when you have return value clashes. For example if null was returned as a valid value in itself, and you needed a way to differentiate between a valid null or an invalid response. This does not appear to be the case here.
My two cents :)
tldr:
I would rather ask why you want to have a method that returns a boolean but the name suggest another thing.
If I have player.GetCurrentHp() and the method returns false if the player has no hp or hp == 0, I would fell that the name is misleading and I would prefer have a player.isAlive() method.
Is not something wrong per se from a logic or software perspective, but I will not help the next developer to work with that code, or yourself in 6 months.
In your case I would go with two methods for LayoutPointer;
public bool IsValid() // <--- I like when boolean methods represent 'is, can, have' actions, ideas, or properties.
{
return _line.positionCount > 1;
}
and
public bool GetLeadingTrailSegment()
{
if (!IsValid())
{
return Vector3.zero;
}
return (lead - _line.GetPosition(_line.positionCount - 2));
}
And then;
public bool IsDrawingOverAllowed(LayoutPointer pointer)
{
if (pointer == null)
{
Debug.LogWarning("IsDrawingOverAllowed: Pointer is null!");
return true; // or false, it depends on your design..
}
if (!pointer.IsValid()) // <-- I also like early returns :D
{
return true;
}
var leadingTrailSegment = pointer.GetLeadingTrailSegment()
return !midline.IsParallelTo(leadingTrailSegment);
}
I know that can be more 'verbose' but remember the idea that create code for machines is easy, but code for humans is harder.. At the end you want to have some code easy to read, understand and maintain.
Side Note; Yes, I know that sometimes can be useful, like in Physics.Raycast but if you are not implementing the TryParse pattern (if you want for example avoid the use of try/catch) I cannot see much gain trying to have just one method that does two things.

OracleDataReader - Handling a NULL field value when setting up a default dropdown SelectedValue

I've got the following code:
// Here is where we will read in all our values and populate the form with them
lblBenCatX.Text = Convert.ToString(reader["Category"]);
lblBenProvX.Text = Convert.ToString(reader["Provision"]);
txtCommentBox.Text = Convert.ToString(reader["Feedback"]);
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
ddlIssue1.SelectedValue = Convert.ToString(reader["Issue_ID"]);
ddlResolution1.SelectedValue = Convert.ToString(reader["Resolution_ID"]);
ddlDefect2.SelectedValue = Convert.ToString(reader["Network2"]);
ddlIssue2.SelectedValue = Convert.ToString(reader["Issue_ID2"]);
ddlResolution2.SelectedValue = Convert.ToString(reader["Resolution_ID2"]);
The first 3 rows of code; no problem. However, if I have a record with a NULL value, the dropdowns break the code. So, I'm thinking I need to check the field first to make sure it's not NULL. Something like:
if (!Convert.ToString(reader["Network"]) = NULL)
{
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
}
However, that's giving me an error:
The left-hand side of an assignment must be a variable, property or
indexer
Any ideas? This is C# in VS2015 with an Oracle back end, if any of that matters.
In C#, you need to use two equal signs in a row == for equality comparison, not one. One equal sign = is an assignment operator.
if (first == second) { ... }
In your case, though, you would want to use the "not equals" != operator:
if (Convert.ToString(reader["Network"]) != null)
Which is cleaner and slightly more-efficent than this:
if (!(Convert.ToString(reader["Network"]) == null))
Note that I've wrapped the whole inner comparison in parens so the whole statement is being negated; otherwise, it will think you're trying to say !Convert.ToString(reader["Network"]), and, as you pointed out in the comments here, you can't use ! with a string.
That being said, if you're converting to string, then it's better to use string.IsNullOrEmpty() for checking:
if (!string.IsNullOrEmpty(reader["Network"].ToString())))
But the best is probably to just check if the column value is null, rather than converting it to string:
if (!reader.IsDBNull(["Network"]))
= is an assignment operator, used when setting values.
== is an equality operator, which determines whether something is equal to something else.
!= is also an equality operator, opposite to the one above. So, when something is not equal to something else.
So actually, you should be using != in this scenario:
if (Convert.ToString(reader["Network"]) != null)
{
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
}
You have a couple of choices. The first is to check if the value is DBNull which is different than an empty string/null value.
if (!reader.IsDBNull([ordinalPositionOfNetworkInSelectStatement]))
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
See IDataReader.IsDBNull. The only thing is that you need to know the ordinal position of the column you are checking.
The alternative is to check for dbnull in your sql select statement and use a function to return an empty string if it is. The positive side of this approach is you do not have to worry about checking for null in your c# code but I am not sure if it has any negative consequences in your oracle query or view. You can do this with COALESCE.
SELECT Category, Provision, Feedback, COALESCE(Network, '') AS Network /*other columns*/
FROM ... -- rest of the query
disclaimer - my oracle syntax is lacking but COALESCE does exist as a function

Why use out keyword instead of assignment in c#?

I've been investigating the out keyword in C# after reading the section about it in C# in Depth. I cannot seem to find an example that shows why the keyword is required over just assigning the value of a return statement. For example:
public void Function1(int input, out int output)
{
output = input * 5;
}
public int Function2(int input)
{
return input * 5;
}
...
int i;
int j;
Function1(5, out i);
j = Function2(5);
Both i and j now have the same value. Is it just the convenience of being able to initialize without the = sign or is there some other value derived that I'm not seeing? I've seen some similar answers mentioning that it shifts responsibility for initialization to the callee here. But all that extra instead of just assigning a return value and not having a void method signature?
Usually out is used for a method that returns something else, but you still need to get a different value from the method.
A good example is Int32.TryParse(input, out myVar) it will return true if it was successful and false otherwise. You can get the converted int via the out parameter.
int myOutVar;
if (Int32.TryParse("2", out myOutVar))
{
//do something with the int
}else{
//Parsing failed, show a message
}
The out / ref keywords in C# should only be used when you need to return multiple values. Even then you should first consider using a container type (such as Tuple) to return multiple values before you revert to out / ref. Whenever you're returning a single value it should just be returned.
A lot of times, using out can help by giving you a slight performance gain.
Consider the TryGetValue method on IDictionary (say myDictionary is an IDictionary<string, string>) Rather than doing this:
string value = String.Empty;
if (myDictionary.ContainsKey("foo"))
{
value = myDictionary["foo"];
}
Both ContainsKey and the indexer need to look up the key in the dictionary, but you can avoid this double-lookup on the positive case by going:
string value;
if (!myDictionary.TryGetValue("foo", out value))
{
value = String.Empty;
}
IMO, that's a decent reason for using out parameters.
Unfortunately we cannot do something like below in C#:
a,b = func(x,y,z);
something that we do in Python or other languages. out kind of overcomes that.
F# has overcome this with tuples I believe.
PS: Returning multiple values from a function might not be good always. Tiny types are good most of the times - http://www.martinfowler.com/bliki/DataClump.html
For example, Int32.TryParse returns boolean if it parsed correctly and with the out parameter changes the value. If the parsed value is 0 and it returns true it means the value you sent to parse was 0. If it returns false then the parser failed.
Some of it is for clarity. Take the TryParse() methods, like
Int32.TryParse("3", out myInt);
This returns a bool that indicates whether the string was able to be parsed into an int.
If you just had
Int32.TryParse("3", myInt);
What happens when that's called? Is myInt assigned? Does TryParse return an int?
It's not readily apparent. But if I have an out parameter, then I know that the value is getting assigned, and that the return is something else.
Basically you do something like (my database read)
if (ReadSingle<UserRecord>(cmd, out user))
Cache.Insert(cacheId, user, null,
DateTime.MaxValue, TimeSpan.FromMinutes(3));
Or else you do something like:
user = ReadSingle<UserRecord>(cmd);
if(null != user)
// Cache.Insert ...
It simplifies the code a little to use a boolean result (that a record was read from the database) and get the actual record into the variable via the out keyword.

Conditional Statements difference

Is there any difference between below two statements
if (null != obj)
and
if (obj != null)
If both treated same which will be preferable?
The first is a Yoda condition. Use it you should not.
The difference here is the code generated. The two will not generate the exact same code, but in practice this will have no bearing on the results or performance of the two statements.
However, if you create your own types, and override the inequality operator, and do a poor job, then it will matter.
Consider this:
public class TestClass
{
...
public static bool operator !=(TestClass left, TestClass right)
{
return !left.Equals(right);
}
}
In this case, if the first argument to the operator is null, ie. if (null != obj), then it will crash with a NullReferenceException.
So to summarize:
The code generated is different
The performance and end results should be the same
Except when you have broken code in the type involved
Now, the reason I think you're asking is that you've seen code from C, which typically had code like this:
if (null == obj)
Note that I switched to equality check here. The reason is that a frequent bug in programs written with old C compilers (these days they tend to catch this problem) would be to switch it around and forget one of the equal characters, ie. this:
if (obj = null)
This assigns null to the variable instead of comparing it. The best way to combat this bug, back then, would be to switch it around, since you can't assign anything to null, it's not a variable. ie. this would fail to compile:
if (null = obj)
No, but the second way is more common and more readable (and more logical in my opinion)
No, there is not. It's exactly the same.
The style null == obj is sometimes just used to prevent the common typo obj = null to not accidently assign null to a variable, but with != there's absolutely no reason to do so.
In .NET it won't actually compile for the typo obj = null.
So the compiler prevents you from accidently doing it.
The Yoda condition comes originally from other languages, where this compiler feature is missing.
They are exactly the same.
Some people prefer to put the null as the first part of the expression to avoid errors like this
if (obj = null) // should be obj == null
But of course this doesn't apply to the != operator, so in your example it's just a difference of style.
First type of statement came from C/C++, where was possible to pass not boolean values to condition verification. E.g. anything not 0 was true, and zero was false:
if (5) { } // true
if (0) { } // false
Sometimes it created problems if you forgot to type one '=' char:
if (x = 5) { } // this was true always and changed x value
if (x == 5) { } // this was true, if x was equal to 5
So, Yoda syntax was used, to receive compiler error in case one '=' was missed:
if (5 = x) { } // this was generating compiler error for absent-minded programmers
if (5 == x) { } // this was true, if x was equal to 5
C# allow only boolean value in conditions, So
if (x = 5) { } // this won't compile
if (x == 5) { } // this is true, if x was equal to 5
What about boolean types?
if (y = true) { }
if (y == true) { }
Well, this is useless code, because you can just write if (y).
Conclusion: Yoda syntax is gone with C/C++ and you do not need to use it anymore.
The use of the first form
if (blah == obj)
stems from the days when compilers would not catch if (obj = blah) i.e. unintentional assignment, unless compile warning level was set to maximum

Do I understand this right? Comparing and assigning in one line of code?

Can someone tell me if I understand this right.
private void SetFontWeight(FontWeight weight)
{
boldButton.IsChecked = weight == FontWeights.Bold;
}
Like what is getting me is how everything is in one line. Like they are comparing and then assigning.
So is there like some order. Logically it seems like it would be like
boldButton.IsChecked = (weight == FontWeights.Bold);
Is that correct it first does comparison then assigns?
Or I guess the long way would be
if(weight == FontWeights.Bold)
{
boldButton.IsChecked = true;
}
else
{
boldButton.IsChecked = false;
}
I also find it kinda weird that they are comparing a struct(FontWeights) to a Class. I would have though it would be like
weight.IsBold == FontWeights.Bold
Yup, equality comparison has higher precedence than assignment. Assignment has basically the lowest precedence, so just about any other operators will be executed before assignment happens.
I'm pretty certain that it's equivalent to
boldButton.IsChecked = (weight == FontWeights.Bold);
This sort of thing was inherited from C (originally) and it has to use parentheses to force assignment first:
if ((x = getcode()) == BAD_CODE) ...
In terms of your misgivings over the comparison, this is just one of the wonderful things that become possible when you're allowed to override comparison operators.
In fact, some would argue that this example makes more sense since you shouldn't have to worry about whether it's the IsBold property that you have to compare. The clas should (and does) figure that out because you're comparing it in a "boldness" sort of way :-)
As far as my understanding is concerned, equality checks will be performed first. No matter you put brackets or not.
Sample code;
public boolean SampleFunction()
{
int a = 1;
int b = 2;
boolean c= false;
c= a==b;
return c;
}
This will first check if a is equal to b. So it will return boolean value and assign it to c.

Categories

Resources