C# string.length > 0 seen as boolean - c#

I am new to C# but not to programming. When I compare the lengths of two strings in the code below, I get the error:
Operator '&' cannot be applied to operands of type 'bool' and 'int'
Apparently string1.Length > 0 is seen as a boolean in this context.
How should I perform this comparison?
if (string1.Length > 0 & string2.Length = 0)
{
//Do Something
}

The reason for the error is because you have written = when you meant ==. In C#
string1.Length > 0 & string2.Length = 0
means
(string1.Length > 0) & (string2.Length = 0)
The type of the left side is bool and the type of the right side is int, which cannot be &-ed together, hence the error. Of course even if you managed to get past that, Length cannot be the target of an assignment either.
Use == to test for equality. = is assignment.
Consider also using && instead of &. The meaning of x & y is "evaluate both, the result is true if both are true and false otherwise". The meaning of x && y is "evaluate the left side; if it is false then the result is false so do not evaluate the right side. If the left side is true then proceed as & does."

When applied to integers, the & operator in C# is a bitwise AND, not a logical AND. Also = is an assignment, not an equality comparison operator. The string1.Length > 0 expression is indeed an expression of boolean type, while the assignment is integer (because 0 is integer).
What you need is
if (string1.Length > 0 && string2.Length == 0)

You probably meant to do this:
if (string1.Length > 0 && string2.Length == 0)
{
//Do Something
}
In C#, the = operator is just for assignment. The == is used for equality comparisons. You probably also want to use the && operator instead of & (&& will skip the second condition if the first condition evaluates to false).
However, if really want to 'compare the lengths of the strings', you can just do this:
if (string1.Length > string2.Length)
{
//Do Something
}

This will fix your problem.
if(string1.Length > 0 && string2.Length == 0)

I think you want a == for your equality test? C# assignment returns a value (as in C).

Related

In what order are boolean expressions evaluated

I have been looking for an explanation for the order in which boolean expressions are evaluated but cannot find one.
Take a look at this statement :
if (locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0)
How is this evaluated.
will it be like this :
if ((locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0)
or like this :
if (locClsTanken.PlaceID == -1 && (locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0))
Is there some documentation about this I dont know the correct search term because english is not my language.
I know I can test it but I would like to find the documentation about this so I can fully understand it
&& has higher precedence than ||, so
locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1 || locClsTanken.DagPrijs == 0
is evaluated as
(locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0
Note that && and || are also short-circuited so evaluation of the right-hand operand only occurs if that could change the result following the evaluation of the left-hand one.
Reference: https://msdn.microsoft.com/en-gb/library/aa691323(v=vs.71).aspx
The expression are readed from left to right in addition to that the && has higher precedence than ||.So in your case it's would be like
if ((locClsTanken.PlaceID == -1 && locRwF.PlaceID > -1) || locClsTanken.DagPrijs == 0)
And the technical therm that you're looking for is
Operators Precedence take a look to this link:Operators Precedence
In C# the compiler moves from left to right, meaning it will evaluate the left most expression first (in your case that is locClsTanken.PlaceID == -1)
Also, && has higher priority than || --> gets evaluated first
However, what might confuse you is how the compiler handels the && and ||. There is a difference between & and &&.
& means both expressions have to be true and both expressions are evaluated. However, && only causes one expression to be evaluated first. If the first expression fails, then the second one isn't even evaluated, because in order for && to be true both expressions need to be true. If the first one already fails && is always false --> && is faster than & and more "inteligent"

how does one compare the date part of a nullable datetime in a linq / lambda query?

I have something like the following:
new ObservableCollection<SomeData>(SomeDataCollection.Where(a => a.AGD_Category.Equals((int)AGD_CategoryEnum.Med) && ((a.AGG_DateStart.Date <= SelectedUntill) && (a.AGG_DateEnd.Value.Date >= SelectedFrom))));
now my a.AGG_DateEnd is a nullable datetime and whenever there is a null value in the list I get an exception because of the "a.AGG_DateEnd.Value.Date" part.
But the thing is, the a.AGG_DateEnd also contains hours and minutes, but I do not want this causes my comparison to give unreliable results.
What can I do to improve?
Thank you,
A quick hack is:
a.AGG_DateEnd.GetValueOrDefault().Date >= SelectedFrom
This is OK because the default(DateTime) (which equals its own .Date) is not greater than any (other) DateTime value.
Otherwise the usual thing to do is:
a.AGG_DateEnd.HasValue && a.AGG_DateEnd.Value.Date >= SelectedFrom
where the double & ensures short-cut evaluation.
Addition after comments:
If you want the opposite answer in the case where it is null, it is:
(a.AGG_DateEnd ?? DateTime.MaxValue).Date >= SelectedFrom
respectively:
!a.AGG_DateEnd.HasValue || a.AGG_DateEnd.Value.Date >= SelectedFrom
Later edit: Since C# 6.0 (July 2015), you can use the ?. operator instead. So use the shorter code:
a.AGG_DateEnd?.Date >= SelectedFrom
which will (formally, at least) compare two nullable values of type DateTime?. When either operand is "null" (i.e. .HasValue gives false), such a comparison gives false.
If you want the opposite bool result in case of null, that is:
!(a.AGG_DateEnd?.Date < SelectedFrom)
Observe how x >= y is different from !(x < y) when we use these lifted operators that operate on Nullable<> values. Any lifted operator (like >= or <) will return false immediately if one of x and y is null; only if both x and y are non-null, will they be unwrapped and the contents compared with the non-lifted operator whose return value will be used.

Operator || cannot be applied to operands of type double and double

I'm building a program that has to check if any of multiple variables are negative but it's telling me that Operator || cannot be applied to operands of type 'double' and 'double'.
if (ASUses || eleven52Uses || UreaUses || PotashUses || FillerUses<0)
{
MessageBox.Show("Error: one or more of the desired outputs is negative");
}
The problem only exists in the first two variables:
(ASUses || eleven52Uses)
Try this:
if (ASUses<0 || eleven52Uses<0 || UreaUses<0 || PotashUses<0 || FillerUses<0)
(Assuming that all variables are double numbers and not bools of course...)
The logical or operator (||) can only be applied to boolean values. While human logic can easily find out the meaning behind your syntax, the compiler can only read it if it adheres to the language specifications, unfortunately.
Also: I would consider writing a function which checks for validity of the variables and not use so many variables in the if statement, as it will be quite hard to maintain code like that.
That's not how it works, you need to separate each statement. or use an array:
if(new []{ ASUses,eleven52Uses,UreaUses,PotashUses,FillerUses }.Any(x => x < 0))
Also you need < 0 if you want to check for negative numbers

What is the difference between & and && operators in C#

I am trying to understand the difference between & and &&operators in C#. I searched on the internet without success. Can somebody please explain with an example?
& is the bitwise AND operator. For operands of integer types, it'll calculate the bitwise-AND of the operands and the result will be an integer type. For boolean operands, it'll compute the logical-and of operands. && is the logical AND operator and doesn't work on integer types. For boolean types, where both of them can be applied, the difference is in the "short-circuiting" property of &&. If the first operand of && evaluates to false, the second is not evaluated at all. This is not the case for &:
bool f() {
Console.WriteLine("f called");
return false;
}
bool g() {
Console.WriteLine("g called");
return false;
}
static void Main() {
bool result = f() && g(); // prints "f called"
Console.WriteLine("------");
result = f() & g(); // prints "f called" and "g called"
}
|| is similar to && in this property; it'll only evaluate the second operand if the first evaluates to false.
Of course, user defined types can overload these operators making them do anything they want.
Strongly recommend this article from Dotnet Mob : http://codaffection.com/csharp-article/short-circuit-evaluation-in-c/
-&& is short-circuit logical operator
For AND operations if any of the operand evaluated to false then total expression evaluated to false, so there is no need to evaluate remaining expressions, similarly in OR operation if any of the operand evaluated to true then remaining evaluation can be skipped
-& operator can be used as either unary or binary operator. that is, unary & can be used to get address of it’s operand in unsafe context.
& can be used on either integral types (like int, long etc.) or on bool.
When used on an integral type, it performs a bitwise AND and gives you the result of that. When used on a bool, it performs a logical AND on BOTH its operands and gives you the result.
&& is not used as a bitwise AND. It is used as a logical AND, but it does not necessarily check both its operands. If the left operand evaluates to false, then it doesn't check the right operand.
Example where this matters:
void Action()
{
string name = null;
if(name != null && name.EndsWith("ack"))
{
SomeOtherAction();
}
}
If name is null, then name.EndsWith("ack") will never get executed. It is smart enough to know if the left operand is false, then the right operand doesn't need to be evaluated (aka "short-circuiting"). That's good because calling a method on null will throw a NullReferenceException.
If you changed it into if(name != null & name.EndsWith("ack")), both sides would get evaluated and it would throw a NullReferenceException.
One detail: & can also be a unary operator (so it has one operand) in an unsafe context. It will give the address of a value or object. It's not important though, as most people don't ever have to touch this part of the language.
Below example and explanation's may help.
Example:
public static bool Condition1()
{
Console.WriteLine("Condition1 is evaluated.");
return false;
}
public static bool Condition2()
{
Console.WriteLine("Condition2 is evaluated.");
return true;
}
1. Logical Operator
& (ampersand) Logical AND operator
| (pipeline) Logical OR operator
Used for ensuring all operands are evaluated.
if(Condition1() & Condition2())
{
Console.WriteLine("This will not print");
//because if any one operand evaluated to false ,
//thus total expression evaluated to false , but both are operand are evaluated.
}
if (Condition2() | Condition1())
{
Console.WriteLine("This will print");
//because any one operand evaluated to true ,
//thus total expression evaluated to true , but both are operand are evaluated.
}
2. Conditional Short Circuit Operator
&& (double ampersand) Conditional AND operator
|| (double pipeline) Conditional OR operator
Used for Skipping the right side operands , Has Side effects so use carefully
if (Condition1() && Condition2())
{
Console.WriteLine("This will not print");
//because if any one operand evaluated to false,
//thus total expression evaluated to false ,
//and here the side effect is that second operand is skipped
//because first operand evaluates to false.
}
if (Condition2() || Condition1())
{
Console.WriteLine("This will print");
//because any one operand evaluated to true
//thus remaining operand evaluations can be skipped.
}
Note:
To get better understanding test it in console sample.
References
dotnetmob.com
wikipedia.org
stackoverflow.com
& is a bitwise operator and && is a logical operator that applies to bool operands.
Easy way to look it is logical & will evaluate both sides of the & regardless if the left side is false, whereas the short-circuit && will only evaluate the right side if the left is true.
d=0;
n=10;
// this throws divide by 0 exception because it evaluates the
// mod even though "d != 0" is false
if ( (d != 0) & (n % d) == 0 )
Console.Writeline( d + " is a factor of " + n);
// This will not evaluate the mod.
if ( (d != 0) && (n % d) == 0 )
Console.Writeline( d + " is a factor of " + n);
The first one is bitwise and the second one is boolean and.
According to - C# 4.0 The Complete Reference by Herbert Schildt
& - Logical AND Operator
| - Logical OR Operator
&& - Short Circuited AND Operator
|| - Short Circuited OR Operator
A simple example can help understand the phenomena
using System;
class SCops {
static void Main() {
int n, d;
n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
d = 0; // now, set d to zero
// Since d is zero, the second operand is not evaluated.
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
// Now, try the same thing without the short-circuit operator.
// This will cause a divide-by-zero error.
if(d != 0 & (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
}
}
Here the & operator checks each and every operand and && checks only the first operand.
As you might notice for 'AND' operations any operand which is false will evaluate the whole expression to false irrespective of any other operands value in the expression.
This short circuited form helps evaluate the first part and is smart enough to know if the second part will be necessary.
Running the program will throw a divide-by-zero error for the last if condition where both the operands are checked for & operator and no exception handling is done to tackle the fact that 'd' can be 0 at any point of time.
The same case applies to '|' in C#.
This is slightly different than C or C++ where '&' and '|' were bitwise AND and OR operators. However C# also applies the bitwise nature of & and | for int variables only.
Hai Friend,
The Operator &&(Logical Operator) is used in conditional statements.
For Instance
if(firstName == 'Tilsan' && lastName == 'Fighter')
{
Response.Write("Welcome Tilsan The Fighter!");
}
the Response.Write statement will run only if both variables firstName and lastName match to their condition.
Whereas & (Bitwise Operator)operator is used for Binary AND operations, i.e., if we write:
bool a, b, c;
a = true;
b = false;
c = a & b;
Response.Write(c); // 'False' will be written to the web page
Here first Binary And operation will be performed on variables a and b, and the resultant value will be stored in variable c.

OR, AND Operator

Newbie question.
How to calculate the value of the formula A f B, where f - the binary function OR or AND?
There is a distinction between the conditional operators && and || and the boolean operators & and |. Mainly it is a difference of precendence (which operators get evaluated first) and also the && and || are 'escaping'. This means that is a sequence such as...
cond1 && cond2 && cond3
If cond1 is false, neither cond2 or cond3 are evaluated as the code rightly assumes that no matter what their value, the expression cannot be true. Likewise...
cond1 || cond2 || cond3
If cond1 is true, neither cond2 or cond3 are evaluated as the expression must be true no matter what their value is.
The bitwise counterparts, & and | are not escaping.
Hope that helps.
Logical OR is ||, logical AND is &&.
If you need the negation NOT, prefix your expression with !.
Example:
X = (A && B) || C || !D;
Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).
If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.
if(A == "haha" && B == "hihi") {
//hahahihi?
}
if(A == "haha" || B != "hihi") {
//hahahihi!?
}
I'm not sure if this answers your question, but for example:
if (A || B)
{
Console.WriteLine("Or");
}
if (A && B)
{
Console.WriteLine("And");
}
Use '&&' for AND and use '||' for OR, for example:
bool A;
bool B;
bool resultOfAnd = A && B; // Returns the result of an AND
bool resultOfOr = A || B; // Returns the result of an OR
If what interests you is bitwise operations look here for a brief tutorial : http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx .bitwise operation perform the same operations like the ones exemplified above they just work with binary representation (the operation applies to each individual bit of the value)
If you want logical operation answers are already given.
&& it's operation return true only if both operand it's true which implies
bool and(bool b1, bool b2)]
{
if(b1==true)
{
if(b2==true)
return true;
}
return false;
}
|| it's operation return true if one or both operand it's true which implies
bool or(bool b1,bool b2)
{
if(b1==true)
return true;
if(b2==true)
return true;
return false;
}
if You write
y=45&&34//45 binary 101101, 35 binary 100010
in result you have
y=32// in binary 100000
Therefore, the which I wrote above is used with respect to every pair of bits
many answers above, i will try a different way:
if you are looking for bitwise operations use only one of the marks like:
3 & 1 //==1 - and
4 | 1 //==5 - or

Categories

Resources