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;
}
Related
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.
Take a look at this code:
System.Web.SessionState.HttpSessionState ss = HttpContext.Current.Session["pdfDocument"] ?? false;
if ((Boolean)ss)
{
Label1.Text = (String)Session["docName"];
}
Basically I want to check if HttpContext.Current.Session["pdfDocument"] is not null, and if it isn't to cast to Boolean, then check if its true or false.
I'm trying to avoid nested if statements and figured there would be a more elegant way to do it. I'm therefore only interested in answers that contain the conditional ? operator.
Any tips?
Why do you use ss variable?
What about this:
if (HttpContext.Current.Session["pdfDocument"] != null)
{
Label1.Text = (String)Session["docName"];
}
object ss = HttpContext.Current.Session["pdfDocument"] ?? false;
if ((Boolean)ss)
{
Label1.Text = (String)Session["docName"];
}
Not sure exactly what you're asking for, how about:
System.Web.SessionState.HttpSessionState ss;
Label1.Text = (Boolean)((ss = HttpContext.Current.Session["pdfDocument"]) ?? false) ? (String)Session["docName"] : Label1.Text;
Should leave ss with either a valid session or null, avoids the problem of trying to store false to ss and completely skips the subsequent 'if'. Though there's a repetition of Label1.Text.
Note: this has been edited to take account of the comment by Dave below.
The problem is that you can't do this:
SessionState.HttpSessionState ss = false;
Try putting your nested ifs into an extension method then call that instead.
HttpContext.Current.Session is an System.Web.SessionState.HttpSessionState object, which is a hash or dictionary, as some may call it, of different objects, so unless you're storing an HttpSessionState object as the "pdfDocument" location the first line is incorrect.
If you're actually storing a bool in the "pdfDocument" location which may or may not already be in this slot, you could cast that directly to a bool and null coalesce it: var ss = (bool)(HttpContext.Current.Session["pdfDocument"] ?? false);.
If you're possibly storing some other kind of object in the "pdfDocument" location you could just see if it's currently at that location by checking for null: var ss = HttpContext.Current.Session["pdfDocument"] != null;.
You can try this, though I don't know if it fits your aesthetics:
bool isPdfDocumentSet =
bool.TryParse((HttpContext.Current.Session["pdfDocument"] as string,
out isPdfDocumentSet)
? isPdfDocumentSet
: false;
EDIT: There is actually an even more concise way of doing it:
bool isPdfDocumentSet =
bool.TryParse(HttpContext.Current.Session["pdfDocument"] as string,
out isPdfDocumentSet) && isPdfDocumentSet;
I think the closest you will get to the solution taking that path is following:
System.Web.SessionState.HttpSessionState ss = HttpContext.Current.Session["pdfDocument"];
if (ss != null)
{
Label1.Text = (String)Session["docName"];
}
My Goal: Extracting one value from an Excel Range, and verify for these cells' value to be the same within this range;
When a cell's value is not the same as the other, I need to return null.
Here's a piece of code:
internal object GetValueFromCells(string start, string end, Formats format) {
// Verifying for empty or null parameters here and throwing accordingly...
try {
Range cells = Excel.get_Range(start, end) as Range;
object value = null;
bool sameValue = false;
foreach(Range cell in cells) {
// This condition block shall execute only once, since 'value' shall not be null afterwards.
if (value == null || value == DBNull.Value)
if (Formats.Formated == format) {
value = cell.Text;
// The following results to be false !?...
sameValue = value == cell.Text; // Shall this not be true?
} else {
value = cell.Value2;
// The following results to be false !?...
sameValue = value == cell.Value2; // Shall this not be true?
}
// This results being always false!?...
// Shall this not be true, I wonder?
sameValue = Formats.Formated == format ? value == cell.Text : value == cell.Value2;
if(!sameValue)
return null;
}
return value;
} catch (Exception ex) {
// Exception handling...
}
}
Reading this code, I would humbly expect a value to be returned when all of the cells in the range have the same value (for instance 334).
However, this methods always returns null (Nothing in Visual Basic)!
Anyone might explain what I'm missing here while this:
value == cell.Value2
always returns false?
Perhaps is it my algorithm that isn't quite right?
EDIT #1
This has solved the problem:
sameValue = Formats.Formatted == format ? cell.Text.Equals(value) : cell.Value2.Equals(value);
I accepted #Jerod Houghtelling's answer as his answer suggests both the ToString() and the Equals() methods to solve the problem.
In addition to it, I dislike having to call the ToString() method, since the value can be numbers, and comparing numbers under a string looks odd to me. So I prefer the Equals() way which I adopted within my solution.
I would like to thank #Sir Gallahad and #Jerod Houghtelling for their good answers. This was the first time I had to face such a situation, and they both helped me better understand what was going on under the hood, plus the others who contributed too through comments.
And thanks to those who upvoted my question. This serves a purpose to demonstrate that I was not so dumb asking! =P Hehehe...
I'm guessing that cell.Value2 is returning a new instance of an object each time you call it. Therefore I would deduce the == is checking to see if both sides of the equation are the same instance of the object. To actually compare the value stored on both side you will have to use the .Equals or convert the values to something that can be compared, for example a string.
sameValue = value.Equals( cell.Value2 );
/* or */
sameValue = value.ToString() == cell.Value2.ToString();
Also I don't see value being set in your example.
Probably the value == cell.Value2 are comparing objects that are from different instances.
Try value.ToString() == cell.Value2.ToString()
What does result.IsVisible equal?
if(a==b)
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
That depends on the values of obj1.status.abc_Report and obj1.AnotherValue.ToBoolean() (and it all depends on whether a==b or not).
I'm not quite sure of what the real question is here - which bit is confusing you?
One bit which may be confusing you is the shortcircuiting && operator (and possibly the lack of bracing!)
The && operator will only evaluate its right hand side if the left hand side evaluates to true: and the overall result of the expression is true if and only if both sides evaluates to true. (I'm assuming no strange user-defined conversions here.)
So another way of writing it would be:
if (a == b)
{
bool visibility = false;
if (obj1.status.abc_REPORT == 'Y')
{
if (obj1.AnotherValue.ToBoolean() == false)
{
visibility = true;
}
}
result.IsVisible = visibility;
}
Note that a condition comparing Booleans, like this:
obj1.AnotherValue.ToBoolean() == false
would usually be written like this:
!obj1.AnotherValue.ToBoolean()
(Note the exclamation mark at the start - the logical "not" operator.)
The same as this, in many less lines:
if (a==b) {
if (obj1.status.abc_REPORT == 'Y') {
if (obj1.AnotherValue.ToBoolean() == false) {
result.IsVisible = true;
}
else {
result.IsVisible = false;
}
}
else {
result.IsVisible = false;
}
}
In simple words:
If a is equal to b:
result will be visible only if:
object1's status's abc_report is Yes(Y = Yes most probably) AND object1's other value cannot be converted to a Boolean
I'm guess result.IsVisible is a boolean
It will be true if the following conditions are true:
obj1.status.abc_REPORT == 'Y'
and
obj1.AnotherValue.ToBoolean() == false
Also, a == b must be true to enter the initial if
lets go line by line:
if(a==b)
obvious if value of a equals value of b the execute following line
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
result is some object (maybe winforms controls etc) which has a property IsVisible set it to true if obj1.status.abc_REPORT is equal to 'Y' and also obj1.AnotherValue.ToBoolean() is equal to false;
Please demonstrate how the ternary operator works with a regular if/else block. Example:
Boolean isValueBig = value > 100 ? true : false;
Exact Duplicate: How do I use the ternary operator?
Boolean isValueBig = ( value > 100 ) ? true : false;
Boolean isValueBig;
if( value > 100 ) {
isValueBig = true;
} else {
isValueBig = false;
}
The difference between the ternary operation and if/else is that the ternary expression is a statement that evaluates to a value, while if/else is not.
To use your example, changing from the use of a ternary expression to if/else you could use this statement:
Boolean isValueBig = null;
if(value > 100)
{
isValueBig = true
}
else
{
isValueBig = false;
}
In this case, though, your statement is equivalent to this:
Boolean isValueBig = (value > 100);
When I was new to C++, I found that it helped to read this construct as follows:
Boolean isValueBig = if condition ? then x else: y;
(Notice that this isn't valid code. It's just what I trained myself to read in my head.)
Boolean isValueBig;
if (value > 100)
{
isValueBig = true;
}
else
{
isValueBig = false;
}
I was never a fan of the ternary operator because I thought it was hard to read. As it so happens, Jon Skeet and his book, C# in Depth finally hit this old dog over the head and got it to sink in. Jon said, and I paraphrase, think of it as a question.
value > 100?
"yes" : "no"
Now the blind can see.
Hope this helps you make it second nature.
Boolean isValueBig;
if(value > 100) { isValueBig = true; } else { isValueBig = false; }
As quoted from the ?: Operator MSDN page, "the conditional operator (?:) returns one of two values depending on the value of a Boolean expression."
So you can use the ternary operator to return more than just booleans:
string result = (value > 100 ) ? "value is big" : "value is small";
PHP Example
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
"The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE."
PHP Documentation on Comparison Operators
Make sure you don't mix types in true/false parts in Java. It produces weird results :-(
Bad example, because you could easily write
Boolean isValueBig = value > 100 ? true : false;
as:
bool isValueBig = value > 100
Beyond that, everyone else has already answered it. I would just not recommend using ternary operators to set bool values, since what you are evaluating is already a boolean value.
I realize it was just an example, but it was worth pointing out.
Others have answered it already but here's one thing you should really know about ternary's usage and by that I mean don't ever do it.
Lets assume that you have a piece of code which is supposed to return a different object for each possible variation of some value, lets say for simpliticy's sake an integer between 1 and 5. Your code looks like this:
if(i==1) {
return new ObjectOne();
} else if(i==2) {
return new ObjectTwo();
} else if(i==3) {
return new ObjectThree();
} else if(i==4) {
return new ObjectFour();
} else if(i==5) {
return new ObjectFive();
} else {
return new DefaultObject();
}
It's easy to understand but a bit heavy. Since ternary is just another way of writing an if..else statement that can be refactored to this
return (i==1) ? new ObjectOne() :
(i==2) ? new ObjectTwo() :
(i==3) ? new ObjectThree() :
(i==4) ? new ObjectFour() :
(i==5) ? new ObjectFive() : new DefaultObject();
It's called nested ternary. It's evil, now that you know about it please never use it. It may seem to have its uses like the case above but it's very likely that in real life situations you would need to use it somewhere where it loses readability (think altering configurations with variable amount of parameters and such).
Bonus sector: Never set attribute values inside if(), just look at this: if(bool=true!=false) { .. }
As quoted from MSDN (noted in a previous post)
string result = (value > 100 ) ? "value is big" : "value is small";
Could be read as:
Is value greater than 100? If yes, string result is "value is big", if no, string result is "value is small".