I need to set the condition as below code.
_orderStatus = Request.QueryString["order"] != null ? Request.QueryString["order"] : _orderStatus != "" ? _orderStatus : "pending";
Currently the condition only applied to show pending order. How can i change and add to get as below condtion:
if Request.QueryString["order"] != null then
_orderStatus: "pending"
else
_orderStatus: "confirmed"
Thanks
should be like this
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
Additional note to the above answer: Let me copy your requirement to the answer:
if Request.QueryString["order"] != null then _orderStatus: "pending"
else _orderStatus: "confirmed"
Here you need to assign the result to the variable _orderStatus, The conditional operator will do that for you, you need not to do an additional assignment within the operator.
While using conditional operator if.. then can be replaced with ?
and else will be replaced by : and the result will be assigned to
the _orderStatus.
Now look into your code( which included in the answer), and apply the replacements as i said. then you will get the answer like the following:
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
The bets way of checking your query string then, try this
if (!string.IsNullOrEmpty(Request.QueryString["order"]))
_orderStatus = "pending";
else
_orderStatus = "confirmed";
There are multiple ways to do either u can simply check the for null or Empty by using if conditon like this
if (!string.IsNullOrEmpty(Request.QueryString["order"]))
_orderStatus = "pending";
else
_orderStatus = "confirmed";
or you can use conditional expression For reference u can go through this link
For your question u can use this way
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
There's no reason to expect any difference in performance.
In my opinion, the ternary operator should only be used if all three operands are very concise and easy to read. Otherwise I think it has the potential to make code harder to read.
I think a lot of people mis-use this operator by using too much logic into one long line of code. I personally won't use it unless the whole line is less than about 80 characters.
Related
This question already has answers here:
Deep null checking, is there a better way?
(16 answers)
Closed 5 years ago.
Can anyone tell me how do I optimize below code.
if (report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) &&
report.Breakdown[reportName.ToString()].Result != null
)
As others have mentioned, you can use the ?. operator to combine some of your null checks. However, if you're after optimizing for performance, you should avoid the double dictionary lookup (ContainsKey and index access), going for a TryGetValue instead:
MyType match = null; // adjust type
if (report?.Breakdown?.TryGetValue(reportName.ToString(), out match) == true &&
match?.Result != null)
{
// ...
}
Ayman's answer is probably the best you can do for C# 6, for before that what you have there is pretty much the best you can do if all those objects are nullable.
The only way to optimize this further is to be checking if those objects are null before even calling the code, or better yet proofing your platform so this particular function shouldn't even be called in the first place if the values are null.
If you are just getting the value from from the dictionary however you can also simplify with the null coalescing operater '??'
Example:
MyDictionary['Key'] ?? "Default Value";
Thus if the Value at that entry is null you'll get the default instead.
So if this is just a fetch I'd just go
var foo =
report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) ?
report.Breakdown[reportName.ToString()].Result ?? "Default" :
"Default";
But if you are actually doing things in the loop, then yeah you're pretty much at the best you can get there.
For C# 6 and newer, you can do it this way:
if (report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null)
You can use null conditional operator but only on C# 6
if ( report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null )
Can you try below? Also probably better to ship it to a method.
// unless report name is already a string
string reportNameString = reportName.ToString();
if ( report?.Breakdown?.ContainsKey(reportNameString) &&
report.Breakdown[reportNameString].Result != null )
{
// rest of the code
}
I am using asp.net mvc view , in order to use if control .
My Code:
<div class="panel-body #(((ObjectModelLibrary.Law)ViewData["currentLaw"]).LastStatus == "" ? "collapse" : string.Empty)">
My Question about above if control:
I want to check
If ((ObjectModelLibrary.Law)ViewData["currentLaw"]).LastStatus == null ||
If ((ObjectModelLibrary.Law)ViewData["currentLaw"]).LastStatus == ""
I want to use ? "collapse" : else : string.Empty)">
How can i use If not null and If not "" in one row in my code?
If you're checking whether a string value is either null or "" then just use IsNullOrEmpty:
string.IsNullOrEmpty(((ObjectModelLibrary.Law)ViewData["currentLaw"]).LastStatus) ? "collapse" : string.Empty
If you want to combine multiple conditions in a conditional expression, you can do so with logical operators. For example:
if (someCondition && someOtherCondition)
This would require that both conditions be true. (If you use the || operator instead then it would require that at least one condition be true.)
So in a ?: operator that might look something like:
(someCondition || someOtherCondition) ? someValue : someOtherValue
Logical segments of conditional expressions can be grouped with parentheses, so you can include as many as you like:
(condition1 || (condition2 && condition3)) ? someValue : someOtherValue
Technically you can construct conditions and other expressions as large as you'd like, though of course code readability and maintainability becomes an issue pretty quickly. Extracting the logic into separate methods helps keep the code more organized.
Something like the ternary operator (?:) or the null coalescing operator (??). It seems silly to me to take up two lines and be so wordy when the other operators exist.
EDIT:
Since it's requested, here's two possible examples of what I hope that I can find
var variable ?= mightBeNull;
or
var variable = mightBeNull != null ? mightBeNull
Really, it's either something that can be used to assign a value, if it's not null, to a variable or an If without an Else packaged nicely in an operator.
The ??= operator is coming to C# 8.
int? i = null; // i = null
i ??= 0; // i = 0
i ??= 1; // i = 0
// different ways of writing 'i ??= 0;':
i = i ?? 0;
if (i == null) i = 0;
So you want this?
if (other != null)
someVariable = other;
You could do the following, but I'd argue that the above is better due to clarity and possible side effects:
someVariable = other ?? someVariable;
The above might cause side effects if someVariable is a property and either the get or set can cause side effects; this shouldn't be important if your property follows the ordinary guidelines. Or, as Servy points out, even if it's a field, it could created different semantics in a multithreaded app. I should note that in the first example, you read other twice, which also has the potential for complexity to enter (though a smaller potential than the latter example).
I bet this is what you are looking for.
Let's say we have a function, myFunction that says whether the argument passed input is null or not. If input is null, it will return "Input is null!", else it will return "Input is not null".
This is the normal approach:
public String myFunction(string input) {
if (input == null)
return "Input is null!";
else
return "Input is not null";
}
And this is the other approach (What you are looking for):
public String myFunction(string input) {
return (input == null) ? "Input is null!" : "Input is not null";
}
It is called (?: conditional operator).
To assign a value to a variable only if it is not null, you would need to use an if. Neither the conditinal nor the null coalesce operators would do that.
if(somethingElse != null) something = somethingElse;
There is no specific operator in C# that does exactly this.
In Visual Studio 2015 C# there is a new operator called the Null-Conditional that does what you are asking. It is the ?. or ? operator.
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null
int? count = customers?[0]?.Orders?.Count(); // null if customers, the first customer, or Orders is null
Currently useable in previous versions of C# but not an operator but rather a one liner would be to use the ? : statement
?: operator
condition ? first_expression : second_expression;
AssingningTO = (someVar == null) ? null: someVar; // if null assign null ELSE assign someVar
AssingningTO = (someVar == null) ? String.Empth(): someVar; // if null assign empty string else someVar
Nullable types can represent all the values of an underlying type, and an additional null value.
http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx
I am new to learning C# and Silverlight and have been given some application files by my employer to start learning. I am able to understand most of the logic, methods and syntax used in C# but there is one line which is very confusing to me. I dont have access to my seniors right now to ask them so the logic behind it so I thought I will ask here.
Take a look at this:
In a .xaml.cs file:
List<object> lst = new List<object>();
lst.Add(GP.mpl.A);
lst.Add(GP.mpl.B);
lst.Add(GP.mpl.C);
lst.Add(GP.mpl.StnNo);
In a different .cs file:
public int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
I understand that StnNo is being received from lst[3] and converted to Integer through
Convert.ToInt32(lst[3].ToString()
But I dont understand this part:
== string.Empty ? 0 : Convert.ToInt32(lst[3].ToString())
Could you tell me what's going on there? I have done multiple searches on google but didn't find anything related. Thanks for any help.
? is a ternary operator.
condition ? first_expression : second_expression;
?: Operator (C# Reference)
So in you example,
public int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
is equal to
public int StnNo;
if (lst[3].ToString() == string.Empty)
{
StnNo = 0;
}
else
{
StnNo = Convert.ToInt32(lst[3].ToString());
}
This is the conditional, sometimes referred to as ternary, operator.
It takes the form boolean expression ? true value : false value.
In C#, the true value and false value must be of the same type, or one must be implicitly convertible to the other (but not both). Otherwise, you must legally and explicitly cast one or both to a common type.
In your code, you have
int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
it is producing the functional equivalent of
int temp;
if (lst[3].ToString() == string.Empty)
temp= 0;
else
temp = Convert.ToInt32(lst[3].ToString());
int StnNo = Convert.ToInt32(temp);
You can see the outer Convert.ToInt32 in your code is actually redundant and can be eliminated.
int StnNo = lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString());
That's a very poorly written way of saying "if lst[3] is empty, then use 0, otherwise parse lst[3]" - because as your question illustrates, it's harder to tell what exactly the original developer intended.
To make it more clear, let's dissect it.
lst[3].ToString() == string.Empty means "does the lst[3] evaluate to an empty string?"
? X : Y means "if so, X, otherwise Y.
0 a constant value
Convert.ToInt32(lst[3].ToString()) parses the value as an lst[3] integer.
Finally the whole expression is passed into another Convert.ToInt32, but this is entirely unnecessary because the result of the conditional expression is always an int.
Since you don't have to call Convert.ToInt32 twice, a better way of writing this would be:
public int StnNo =
(lst[3].ToString() == string.Empty
? 0
: Convert.ToInt32(lst[3].ToString()));
An even better way of writing this would be:
int StnNo;
int.TryParse(lst[3], out StnNo);
It's more lines of code, but it's a lot easier to read.
== string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()) is to check that if lst[3] does not contain any value, then 0 will be assigned to StnNo.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Do you find the following C# code legible?
private bool CanExecuteAdd(string parameter) {
return
this.Script == null ? false
: parameter == "Step" ? true
: parameter == "Element" ? this.ElementSelectedInLibrary != null && this.SelectedStep != null
: parameter == "Choice" ? this.SelectedElement != null
: parameter == "Jump" ? this.SelectedStep != null
: parameter == "Conditional jump" ? false
: false.Throw("Unknown Add parameter {0} in XAML.".F(parameter));
}
where Throw is defined as:
public static T Throw<T>(this T ignored, string message) {
throw new Exception(message);
}
I know that's not idiomatic C#. However, would you be able at understand it at first or second glance? Or did I stray too far?
Why not use a switch? I think it's way more readable.
private bool CanExecuteAdd(string parameter) {
if (Script == null)
return false;
switch (parameter) {
case "Step":
return true;
case "Element":
return ElementSelectedInLibrary != null && SelectedStep != null;
case "Choice":
return SelectedElement != null;
case "Jump":
return SelectedStep != null;
case "Conditional jump":
return false;
default:
throw new Exception(string.Format("Unknown Add parameter {0} in XAML.", parameter));
}
}
I've used this sort of code in Java a fair amount. I don't like the false.Throw bit, but having multiple conditionals like this (particularly formatted this way) is fine in my view.
It's slightly strange the very first time you see it, but after that it's just a handy pattern to know about.
One alternative to using false.Throw here would be something like this:
bool? ret = this.Script == null ? false
: parameter == "Step" ? true
: parameter == "Element" ? this.ElementSelectedInLibrary != null && this.SelectedStep != null
: parameter == "Choice" ? this.SelectedElement != null
: parameter == "Jump" ? this.SelectedStep != null
: parameter == "Conditional jump" ? false
: null;
if (ret == null)
{
throw new ArgumentException(
string.Format("Unknown Add parameter {0} in XAML.", parameter);
}
return ret.Value;
EDIT: Actually, in this case I wouldn't use either if/else or this pattern... I'd use switch/case. This can be very compact if you want:
if (this.Script == null)
{
return false;
}
switch (parameter)
{
case "Step": return true;
case "Element": return this.ElementSelectedInLibrary != null && this.SelectedStep != null;
case "Choice": return this.SelectedElement != null;
case "Jump": return this.SelectedStep != null;
default: throw new ArgumentException(
string.Format("Unknown Add parameter {0} in XAML.", parameter);
}
My rule of thumb: use expressions for things with no side effects. Use statements for things with one side effect and for control flow.
Throwing is effectively a side effect; it does not compute a value, it alters control flow. You're computing a value, computing, computing, computing, and then boom, side effect. I find code like that confusing and vexing. I say that control flow should be in statements, not the side effect of something that looks like a computation.
I vote for non-legible.
Although the syntax is correct, it's somewhat convoluted and since it's not, dare I say, "traditional", many developers will have to waste time trying to ensure they understand what they're reading. Not an ideal situation.
Readability is definitely one key ingredient to good coding, and I would say your sample isn't immediately readable for most devs.
I really don't like this code. It took me more than about 15 seconds to understand, so I gave up.
An if/then would be preferable.
I like the conditional operator, and use it a lot.
This example is a little confusing, because the nature of the operator is not clear from the layout and usage.
At the very least I like to make the choice and alternatives clear by using this formatting:
choice
? true-case
: false-case
But if we apply that to your code it reveals the lack of clarity in using the construct this way:
return
this.Script == null
? false
: parameter == "Step"
? true
: parameter == "Element"
? this.ElementSelectedInLibrary != null && this.SelectedStep != null
: parameter == "Choice"
? this.SelectedElement != null
: parameter == "Jump"
? this.SelectedStep != null
: parameter == "Conditional jump"
? false
: false.Throw("Unknown Add parameter {0} in XAML.".F(parameter));
This feels to me like we're trying to use the conditional operator like a switch statement, where a switch statement, or better yet a design pattern like the Command Pattern would be much clearer.
Convert your nested ternary into a switch. Never coerce one control structure into doing poorly or illegibly what a built-in structure will do perfectly, especially if there's no obvious benefit.
Why not use a nullable type bool?
private bool? CanExecuteAdd(string parameter) {
return
this.Script == null ? false
: parameter == "Step" ? true
: parameter == "Element" ? this.ElementSelectedInLibrary != null && this.SelectedStep != null
: parameter == "Choice" ? this.SelectedElement != null
: parameter == "Jump" ? this.SelectedStep != null
: parameter == "Conditional jump" ? false
: null;
}
At first I was horrified, but actually I can't think of a way to write this much clearer in C# - I was trying to think of something where you had an array of Funcs mapped to results, but it got even uglier.
Even though parsing through the actual conditionals is rough, it's at least easy to grok the intent, though I'd prefer to use a switch block and handle everything else as a special case.
Being non-idiomatic means that you're forcing the reader to spend time thinking about whether or not what they're reading means what they think it means.
So being legible doesn't buy the sophisticated (namely, suspicious) reader very much. This strikes me as a case of being clever for the sake of being clever.
Is there any reason not to use a switch or an else if construct here?
Too hard to read, take care of exceptions first.
Handle each case in it's own if, then you can have more complex conditions.
This is one of the few times, this many separate returns in a method would be acceptable
private bool CanExecuteAdd(string parameter)
{
if (this.Script == null)
return false;
if (parameter.NotIn([] {"Step", "Element", "Choice", "Jump", "Conditional jump"})
throw new Exception("Unknown Add parameter {0} in XAML.".F(parameter));
if (parameter == "Step")
return true;
if (parameter == "Element")
this.ElementSelectedInLibrary != null && this.SelectedStep != null;
// etc, etc
}
Oh, and the .NotIn is an extension method, the opposite of this, I would imagine (can't say this is quite exact to what is needed)
public static bool In<T>(this T obj, IEnumerable<T> arr)
{
return arr.Contains(obj);
}
It looks fine to me, but I'd alter your Throw method to:
static TObject Throw<TObject, TException>(this TObject ignored, TException exception)
{
throw exception;
}
That allows you to specify the kind of Exception thrown.
Unfortunately the ternary operator (?:) isn't a common idiom in the C languages--I've met many C, C++ and C# developers who have to pause to read it because they aren't familiar with it or don't use it. That does not make it a bad language feature or illegible, however those same developers may call OP's example illegible because it nests a language feature they're uncomfortable with.
I don't find the example illegible--I've seen nested ternary operators many times. However, I do feel that using a switch would be a preferable choice for checking 'parameter' against the strings.
Far more galling to me is that Throw extension method that ignores the 'this' parameter. What would 42.Throw(...) mean? If I were reviewing the code I would call it out as bad design.
In C & C++, the described use is idiomatic and the reason for the operator. The benefit of the ternary conditional vs. a chained if-then-else is that it's an expression with a known type. In C++, you can actually write
foo_t foo = bar_p ? bar
: qux_p ? qux
: woz_p ? woz
: (throw SomeExpression(), foo_t())
;
Notice the comma operator, which returns a foo_t that will never be constructed due to the throw.
I've actually never seen the ternary operator pushed out so far. However, I understood where you were going. Also, I agree with Jon, I don't like the false.Throw part.