What does variable = !variable mean? - c#

I have this code. What does it mean?
bool q = false;
if (i < 0) {
q = !q;
}
I assume !q means true?
UPDATE: The full code is below. When ! is used in the IF statement, is the variable in that situation always false?
bool q = false;
if (i < 0) {
q = !q;
}
if (!q) {
/// do stuff
}

All it means is it's "not q", so it's opposite of whatever q is.

In the case of a boolean like here, the variable q can be either true or false.
when you put a ! in front of something in most languages, it means "opposite"
As example,
1 != 2
means:
1 is opposite of equal to 2
.
This being for a condition, in your case, it would mean
assign the opposite of q to q.
Also, I believe most people on SO (Stack Overflow) will tell you this question does not belong here because you can find it easily on the internet, if you want, there are various books to learn programming. You can search "it ebooks" on the internet and you will probably find many for free .

As the other poster said, it switches the bool property from true to false. In your example, q starts as false. If i is less than 0 then q becomes true. Then comes the if statement, which says "if q is false, then execute the next code block". q only stays false if i is greater than or equal to 0. So no, the code inside your if block will not always execute. It depends on i.

Related

In C#, what does an expression x = y == z stand for?

Please forgive me the noob question, but C# is not my native language. In code I took over, I stumbled upon
var success = true;
success = Upload.Status == FileStatus.Ok;
In there, FileStatus is of type enum, somewhere custom defined. I guess, success is essentially non-nullable Boolean. I think that the 2nd line sets success to false if (and only if) Upload.Status == FileStatus.Ok, which would also induce that the latter two variables should be of same type.
Could you please let me know, whether my hypotheses are correct? Also: How is such a construct called? What is it short for?
success is going to be a bool.
It is initialized with true, but that should be unessesary.
var success = true;
And will then be set to the result of (Upload.Status == FileStatus.Ok) which is a bool.
success = Upload.Status == FileStatus.Ok;
Think of it as success = (Upload.Status == FileStatus.Ok); if that helps.
And yes, it took me a moment to parse it too. I have a profound dislike for people trying to save lines at the cost of readability. I would use this:
if(Upload.Status == FileStatus.Ok)
success = true;
else
success = false;
Maybe use the shorter if syntax.
Upload.Status == FileStatus.Ok evaluates to a bool, either true or false. success will be assigned the result of that evaluation.
It's no more mystical than var sum = 4 + 5; resulting in sum being assigned a value of 9.
It's assigning the result of an expression to a variable, same as var x = 1 + 2; just that in this case the expression is of type bool.
Needlessly verbose, this would be the same:
bool success;
if (Upload.Status == FileStatus.Ok)
{
success = true;
}
else
{
success = false;
}

What is the Technical Term for C# inline variable assignment and evaluation?

I was reading through some code on Github recently and i came across the following line,
if (((tmp = rx.IndexOf("<")) >= 0) && (rx.IndexOf(">") > tmp ))
specifically the
(tmp = rx.IndexOf("<") >= 0)
And the immediate use of the tmp variable in a comparison in the same line in the next part of the if statement
(rx.IndexOf(">") > tmp )
in which a variable is being set by a string,indexOf() method, and then the 'assignment statement itself' is being evaluated with a greater-or-equal-to equality operator.
At first i thought this was a typo, but on evaluating the code via a simple console app, i found it to be valid, and a great shortcut.
The question is "What is the technical term for this?" as i could find no explanation in various C# help sites.
An example console app to demonstrate how the statement was used.
public static void Main()
{
// first test - the actual code I found in gitHub
int tmp;
int tmp2;
string rx = " < test>";
// the below line is the subject of the question.
if (((tmp = rx.IndexOf("<")) >= 0) && (rx.IndexOf(">") > tmp )){
Console.WriteLine("The Close brace is after the opening brace!");
}
// additional test
int r;
Console.WriteLine(r = 25 + 3);
Console.WriteLine(r);
// and another
int w = -1;
Console.WriteLine(" The index of '<' is greater than 0 : " + _
((w = rx.IndexOf("<")) > 0).ToString() + _
" and the value of w is " + w.ToString());
}
The output of the above code is below.
Again , I understand the code works, I would like to know what is this called technically?
The Close brace is after the opening brace!
28
28
The index of '<' is greater than 0 : True and the value of w is 2
There is no "technical term".
It's an assignment, and a assignment can act as expression or a statement.
It's a statement that has a value; Or an Expression where the result value can be ignored. (Unlike x+y, the Result is not allowed to be ignored)
It's the same as the prefix and postfix operators i++;
It will look less like "inline" in a line like x = y = z;
However, it's not often used, cause it's less readable, as you just proofed.
And in your case, assigning a value and using the value in the same expression tree
highly depends on evaluation order, which is well defined, but who knows it by heart ?
This style of writing will safe you a line of code (by making one line longer)
but it will never save you any operation, hence not cause any performance.
So Read it, Understand it, but better don't use it frequent.
This is just a consequence of assignment being an expression. It is defined in the C# specification:
7.17.1 Simple Assignment
The = operator is called the simple assignment operator.
The result of a simple assignment expression is the value assigned to
the left operand. The result has the same type as the left operand and
is always classified as a value.
So the value of
tmp = rx.IndexOf("<")
is the value assigned to tmp which is rx.IndexOf("<"). This value is then compared to 0 in the outer expression.

Assign inside or out of loop?

I would like to assign a value if P true then run a while loop with P.
This is the obvious solution:
int thevalue = 0;
// Calculate P
if(P)
{
theValue = 2;
}
while(P)
{
// Do something without modifying theValue and calculate P
}
But this looks nicer to me:
int theValue = 0;
// Calculate P
while(P)
{
theValue = 2;
// Do something without modifying theValue and calculate P
}
Will it assign every time the loop runs? Compiler could optimize this.
Is it a good practice?
EDIT:
The value is used after the loop.
The value should not change if P false when it examined.
More clear question:
If the while loop runs like a "billion times" is the assign in the loop ineffective and an unnecessary CPU cycle?
Functionally it is equivalent, but I'll address the 'good practice'...
P is clearly not invariant since otherwise your while loop would never terminate! If it's not invariant then the starting/initial condition you use in your 'if' statement must be different from the evaluation for each iteration of the loop.
I think what you are really trying to say with the 'if' statement is "set the value if the while loop will be evaluated at least once". As a matter of style I would write the code to make this intent clearer. If you can use a collection then I would suggest a pattern such as....
var theValue = collection.Any() ? 2 : someSensibleDefault;
foreach (var thing in collection)
{
}
If it truly is a test condition...
var theValue = (initialP) ? 2 : someSensibleDefault;
while (P)
{
}
As a final comment, I really wouldn't consider worrying about optimisation here - the goal should be to express what you trying to do.

Can you Make a Boolean value turn off/on automatically?

Okay I have declared a Key CellX to boolean value True. In a sense as long as this value remains true my data will keep inserting in and If I turn it false it will stop at what ever count it was on. Now I have to Stop at when 400 orders have been inserted in data base and no more... can I actually apply a condition
like
Key CellX "True"
if CellX ==400 then "False"
else
"True"
can we accomplish this... I am doing in C#.
I C most of you have given good logic.
little more CellX is declared in web.xml along with other keys such as CellA, B, C and A, B, are receiving data in DB so to stop it from reaching 400 I can manually change the CellX Boolean Value or How can I implement a condition which will make my Boolean value to turn false when Cell A, B, C reach 400.
You can do something like
myBool = (CellX == 400);
However, in your post you refer to CellX as both a boolean and as something that can be compared to an integer value of 400. A given variable can be boolean or an integer.
If CellX is your boolean, instead do something like:
CellX = (myLoopCounter == 400);
The syntax
myBool = (myLoopCounter == 400);
evaluates like this:
Evaluate whether myLoopCounter is exactly 400 (true, or false)
Assign the result of the previous step to myBool
A variable can't be dynamically evaluated like that (at least not in the way I think you're looking for, things like Func notwithstanding). But you can create it as a read-only property on the class which would be evaluated each time (since a property is mainly a syntactically different form of a method call):
private bool LimitReached
{
get
{
return (CellX == 400);
}
}
So if you keep checking the value of LimitReached over and over, it should potentially change if the value of CellX is also changing.
Is this what you're trying to do?
int Counter = 1;
bool Continue = true;
while(Continue)
{
// Insert one row
if (Counter == 400)
Continue = false;
Counter++;
}
This can also be written:
for(int i = 0; i < 400; i++)
{
// insert one row
}

Help with a C# conditional statement dealing with Strings

In my attempt at dissecting a bit of C# I am afraid I do not understand either the goal or the logic of this bit of code:
if (!string.IsNullOrEmpty(str2) && (Strings.UCase(Strings.Left(str2, 1)) != Strings.Left(str2, 1)))
{
return false;
}
I understand the first part is checking if str2 is "not null", however the second part is coming off a bit flaky. So we UCase the first character of str2, and if it does not equal the first character of str2 (which is NOT "UCase"d), then return "false"?
Maybe I am not missing anything and what I described above is in fact what the code is doing. If this is the case, can we reform this into something else that offers the same result,say for example, check if str2 is uppercase or not? I feel like this is the end goal.
You thoughts?
Yes, you understood the code right.
It looks like something translated from VB using a translation tool, as it's using functions from the VisualBasic namespace. I would rather write it with String methods:
if (!String.IsNullOrEmpty(str2) && str2.Substring(0,1).ToUpper() != str2.SubString(0,1)) {
return false;
}
Or simply getting the first character as a character instead of as a string, and use the IsLower method of the Char class:
if (!string.IsNullOrEmpty(str2) && Char.IsLower(str2[0])) {
return false;
}
My bet is that they are really just testing whether the first character is uppercase. The initial "IsNullOrEmpty" test is just there to make sure that the real test doesn't throw an exception.
The big question: if there is no string value (null or empty) this will not return false. Is that the expected outcome?
Code Objective in English :)
If the non-empty string begins with a lower case character then return false
This is the same, but refactored:
if (!string.IsNullOrEmpty(str2)) {
string s = Strings.Left(str2, 1);
if (Strings.UCase(s) != s) {
return false;
}
}
It is clear that this code tests that the first letter of str2 is or isn't in uppercase when it has any character.
I share the perceptions you have when you say : "I do not understand either the goal or the logic of this bit of code" :) A test that returns only 'false is "fishy" : presumably "something" is waiting for a boolean to be returned, and nothing is returned if the result of this evaluates to 'true.
But if I had to write such a function I'd use the alternative OR logic :
return (! (String.IsNullOrEmpty(testString) || testString.ToUpper()[0] == testString[0]));

Categories

Resources