How to use ?: operator [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How would I convert the following code to use the ?: operator.. Is it Possible?
tbtotalamount.Text = string.Format("{0:n2}", dtl.Compute("sum(NetPay)", ""));
if (tbtotalamount.Text.Length == 0)
{
tbtotalamount.Text = "0";
}

The quoted code wouldn't benefit from using the ? : operator, which is called the conditional operator (sometimes called "the ternary operator" although technically, it's only a ternary operator — e.g., an operator that has three operands).
Typically the conditional operator is handy for when you have a variable and want to assign one of two values to it on the basis of a condition. So code in this form:
if (someCondition) {
a = "one value";
}
else {
a = "a different value";
}
can be rewritten
a = someCondition ? "one value" : "a different value";
In your case, though, you don't know that tbtotalamount.Text is blank until after you've done the string.Format, so you're better off leaving it with the if.

Yes. Here's how:
string test = string.Format("{0:n2}", dtl.Compute("sum(NetPay)", ""));
tbttotalamount.Text = test.length == 0 ? "0" : test;
Sorry to see so many downvotes, I'm not familiar with the ? (ternary) operator for a very long time either. I think it is very handy.
To the left of it is your test expression, it should be a boolean after evaluation. To the right is what the operator returns: if true, it will return the value to the left of the :. If false, the value to the right. Note that the whole expression returns something, and the compiler needs you to do something with it. You can't use the ternary operation to replace if-else statements that call functions whose return type is void.
What I mean to say is that a lot of people who've never used it before (like me) seem to think this is a pure if-else replacement, which it is not.

Related

Confusing with LINQ and Lambda expressions in C# [duplicate]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I need a discussion regarding the Performance of LINQ and Lambda Expression.
Which one is better?
I guess you mean query expression when talking about LINQ here.
They are equivalent. The compiler changes the query expression into the equivalent Lambda expression before compiling it, so the generated IL is exactly the same.
Example
var result = select s from intarray
where s < 5
select s + 1;
is exactly the same as
var result = intarray.Where( s => s < 5).Select( s => s+1);
Note that if you write the query expression like this:
var result = select s from intarray
where s < 5
select s;
It's converted to:
var result = intarray.Where( s => s < 5);
The final call to Select is omitted because it's redundant.
a quick comparison in reflector would probably do the trick. However, from a 'preference' standpoint, I find lambda statements easier to follow and write and use them across the board whether it be with objects, xml or whatever.
If performance is negligible, i'd go with the one that works best for you.
i actually started off a little topic looking at linq methods which may be of interest:
What's your favourite linq method or 'trick'
cheers..

Rewrite Contains() method C# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I Have this clausule
if ((line.Contains('%')) || (line.Contains('#')) || (line.Contains("") && (!line.Contains(','))))
and i want rewrite it to one method,beacause this is too slow. Any ideas??
if(line.Intersect("%#,").Any())
or
if("%#,".Intersect(line).Any())
(Reversing the parameters may improve performance, depending on the type of data in line and the percentage of characters that match.)
Both the other answers seem to ignore the fact that the original code returns true when line contains % or # or when it does NOT contain ,. (the empty string being totally irrelevant).
The correct way to write this would be:
if(line.Intersect("%#").Any() || !line.Contains(","))
Or possibly:
char[] includes = { '%', '#' };
char[] excludes = { ',' };
if(line.Intersect(includes).Any() || !line.Intersect(excludes).Any())
Or this:
char[] includes = { '%', '#' };
char[] excludes = { ',' };
if(line.IndexOfAny(includes) != -1 || line.IndexOfAny(excludes) == -1)
First, lets simplify the whole statement. You use to many hooks:
if (line.Contains('%') || line.Contains('#') || line.Contains("") && !line.Contains(','))
Second, as stated before, line.Contains("") will always return true. Perhapse you are missing a space or something.
Last, searching a string (or an array of characters) for the orrucance of a character is FAST! The whole search-operation is just one simple operation at assembly level (REP SCASW). In this case you have to search for more than once characters, which will result in one or more simple assembly instructions. Other statements in C# are perhapse shorter, but probably not faster.
Search for a string inside a string is slightly slower, so try to remove the Contains("").
Other operations (with LINQ or REGEX) will probably result into more: memory-operations (for arrays, delegates, result types), more analyzation (multiple characters inside an array of characters), etc. etc.

Converting Doubles to strings [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
When I remove the ToString() in the method below, I get no error, so why is it necessary?
public string BuildEquation()
{
switch (Choice)
{
case "A":
return mNumber1.ToString() + "+" + mNumber2.ToString();
case "S":
return mNumber1.ToString() + "-" + mNumber2.ToString();
case "M":
return mNumber1.ToString() + "*" + mNumber2.ToString();
default:
return mNumber1.ToString() + "/" + mNumber2.ToString(); // corrected
}
}
From the C# Language Specification 1.2, §7.7.4, Addition operator:
String concatenation: The binary + operator performs string
concatenation when one or both operands are of type string. If an
operand of string concatenation is null, an empty string is
substituted. Otherwise, any non-string argument is converted to its
string representation by invoking the virtual ToString method
inherited from type object. If ToString returns null, an empty string
is substituted. [...] A System.OutOfMemoryException may be thrown if
there is not enough memory available to allocate the resulting
string.
In other words, the + operand will do the ToString conversion for you.
so why is it necessary?
It's not necessary.
Some people may subjectively consider it more readable to include it, but omitting it not only doesn't result in any errors, but it also produces the exact same output. There is no functional change in omitting the ToString calls.
Concatening double and string together converts it for you.
Otherwise you can convert it with .ToString()
Or use Convert.ToString(double) method. http://msdn.microsoft.com/en-us/library/c309e6c9.aspx
It's because you are concatenating with a string already ("+", "-", etc), which means the rest of the expression is resolved to a string type. If you didn't concatenate those extra strings, then you would need to call ToString().

Problem with C# conditional [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Hi I have the following code:
medianListTester.cfyPE = 0;
if (medianListTester.cfyPE != 0 || testStock.getCEPS() != 0)
{
medianCYPE_price = medianListTester.cfyPE * testStock.getCEPS();
counter++;
}
else
//do something else
but it doesn't seem to "do something else" and still fires the code inside the conditional. Am I doing something wrong here? Why won't it run the code in the if statement?
If testStock.getCEPS() is not 0 you will not hit the else block. Depending on what you need and what you are expecting you might need to use && instead of || ?
medianListTester.cfyPE is set to 0, so the first clause in your if statement evaluates to false. What does TestStock.getCEPS()? If that is non-zero, then that will evaluate to true, and the entire if statement is then true.
I can't really tell what you're asking, but you're calling getCEPS() twice, and perhaps that is returning two different values, and perhaps that is causing your trouble.
Try this instead:
medianListTester.cfyPE = 0;
var ceps = testStock.getCEPS();
if (medianListTester.cfyPE != 0 || ceps != 0)
{
medianCYPE_price = medianListTester.cfyPE * ceps;
counter++;
}
else
//do something else
It sounds like testStock.getCEPS() is returning something other than 0. That would explain why it never hits do something else. Have you checked what this is returning?
What's the value of the call to testStock.getCEPS()? If that's not 0 it will still enter that code block. Also, I don't know the details of the object referenced by medianListTester, but it is possible that there is a getter/setter that isn't working right.
Your best bet for solving this is to print out or somehow look at the values of both medianListTester.cfyPE and testStock.getCEPS() right after the assignment but just before the if statement.

||(Or) Logical Operator in Java vs .Net [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I have been coding in Java(Mainly) and .Net for a while.
What I found is that the || logical operator in .Net is different in result to the || operator in Java.
Lets look at the following Java code:
Object obj = null;
if(obj == null || obj.toString().isEmpty()){
System.out.println("Object is null");
}
The result of the code above will be:
Object is null
The reason for that is because obj == null is true and the second expression wasn't evaluated. If it was, I would have received a java.lang.NullPointerException.
And if I used the single or (|) I would also received a NullPointerException (Both are evaluated).
My question is the following:
If the code was C#, I will always get a ObjectReferenceNotSet etc. exception because the obj value is null and the second expression is always evaluated (Regardless of the operator), meaning the result is different in C# than in Java.
If I would to change the C# code to work properly, I have to create two if statements.
Is there not an easier way to do this in C# to be similar to Java? (Keep it in one if with 2 expressions)
Thank you.
The || operator in C# is short-circuiting, just like in Java. As is &&. The | and & operators are not short-circuiting, just like in Java.
If your results are different, there is a bug in the code. Can you show us the offending C# please?
This works fine:
object obj = null;
if(obj == null || string.IsNullOrEmpty(obj.ToString())) {
Console.WriteLine("Object is null");
}
The || operator has exactly the same meaning in Java and C#. It is called a conditional logical OR, or "short-circuiting" logical OR operator:
http://msdn.microsoft.com/en-us/library/6373h346%28VS.71%29.aspx
This behaviour is a strict java language feature:
At run time, the left-hand operand
expression is evaluated first ;[...] if the resulting value is
true, the value of the conditional-or
expression is true and the right-hand
operand expression is not evaluated.
If the value of the left-hand operand
is false, then the right-hand
expression is evaluated; [...] the
resulting value becomes the value of
the conditional-or expression.
Thus, || computes the same result as |
on boolean or Boolean operands. It
differs only in that the right-hand
operand expression is evaluated
conditionally rather than always
Similar rules are defined for the java conditional-and operator.
Compare (identical) to C#:
The && and || operators are called
the conditional logical operators.
They are also called the
“short-circuiting” logical operators.
conditional-and-expression:
inclusive-or-expression
conditional-and-expression && inclusive-or-expression
conditional-or-expression:
conditional-and-expression
conditional-or-expression || conditional-and-expression
The && and || operators are conditional versions
of the & and | operators:
The operation x && y corresponds to the
operation x & y, except that y is
evaluated only if x is not false.
The operation x || y corresponds to
the operation x | y, except that y is
evaluated only if x is not true.
It's called "short circuit evaluation". There is no need to evaluate the next statement. This is a nice feature in Java.

Categories

Resources