c# 9 contextual keywords or,and,not [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Based on msdn, C# 9 includes new "and", "or" and "not" keywords. I do not understand why, or when, one should use "or" instead of "||", "and" instead of "&&", etc.
What problem does the contextual keywords "or", "and", and "not" solve that the original conditionals ("||", "&&", etc.) didn't?

You could do:
if (a == 1 || a == 2)
or
if (a == 1 or 2)
The 2nd version is shorter and, in theory, easier to parse as a human.
It's also easier to write
if (a is (>2 and <4) or (>5 and <7) )

You're likely referring to C# 9's pattern matching. (https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements)
Using "and" and "or" is to ensure that binary operations are not ambiguous to the compiler.
This article contains more information:
https://www.infoq.com/news/2020/07/CSharp-And-Or-Not/

Borrowing Neil's example and Paurian's linked article, let's say you have this:
bool? x = SomeFunction();
if (x == null || x == true) { SomeOtherFunction(); }
x
Result
true
function called
false
function skipped
null
function called
With the introduction of pattern matching, we don't have to say x == twice. Instead we can say:
if (x is null or true) { SomeOtherFunction(); }
If we didn't have is and or as a context-sensitive keywords and used == and || instead, it would be ambiguous to the compiler, because this expression can mean something else in a pre-Patterns world.
That pre-Patterns expression is:
if (x == null || true) { SomeOtherFunction(); }
Which gives a different result for the case where x is false.
x
Result
true
function called
false
function called
null
function called
So to avoid this ambiguity, the language designers added separate keywords. See this comment on the GitHub thread for these keywords.

It's just syntactic sugar for comparing values against constant expressions. When you need to compare a variable or property to one or more constant values, you can use these Logical Patterns to shorten your code and improve readability.
This is also useful when paired with switch expressions; as per the documented example:
static string Classify(double measurement) => measurement switch
{
< -40.0 => "Too low",
>= -40.0 and < 0 => "Low",
>= 0 and < 10.0 => "Acceptable",
>= 10.0 and < 20.0 => "High",
>= 20.0 => "Too high",
double.NaN => "Unknown",
};
Here, we can execute a case based on a range of numbers aided by Logical Expressions.
Since enum values are constant, we can also use this pattern like so:
enum E {
A,
B,
C,
}
E e = E.A;
// Using logical expressions:
bool logical = e is E.A or E.B;
// V.S. the more wordy.
bool standard = e == E.A || e == E.B;

Related

Compare two strings to a value in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
string 1= reportCard.1.GetText();
string 2= reportCard.2.GetText();
string 3= reportCard.3.GetText();
string 4= reportCard.4.GetText();
string 5= reportCard.5.GetText();
How do I write an if statement which check if any of the above values is false. I need to write an or operate and compare to a Y/N value
if ((1||2||3||4).Equals("No"))
This is giving error - "Cannot be applied to operands string"
I'd advise against using == to test string equality. Use String.Equals() instead.
You can also do this in one statement using Linq:
if ((new [] {string1, string2, ...}).Any(s=>string.equals(s,"No",StringComparison.CurrentCultureIgnoreCase)))
{
DoStuff();
}
This will DoStuff() if any of your strings are equal to "no" ignoring the case.
See String.Equals() and Enumerable.Any() for further reading. It should be noted that an Enumerable is any class that can be enumerated, so this includes almost all collections like arrays and lists.
Replace string1,string2,... with all of your string variable names. I'd also advise changing your report card class to have a List<string> of results (assuming all of your results are strings) rather than these fields. That way you could enumerate over it like a collection.
See List<T>.
You also can't have variable names that start with strings.
If you absolutely HAVE to use ORs, you need to perform each comparison separately and then chain them together. The way you've done it essentially reads "if string1 or string2 or string3 or string4 equals "no"". Which will evaluate as though you're saying ((string1 or string2) or (string3 or string4)) equals "no".
Obviously, "apple or pair" isn't a valid operation. So what you want is "string1 equals "no" or string2 equals "no" or string3 equals "no"...
To do this in C# you'd use something like:
if (string1 == "No" ||
string2 == "No" ||
stringN == "No" ||)
{
DoStuff();
}
I'd strongly advise against using this approach though as it's poor practice. Even if it's beyond the scope of your assignment, read up on the links I've posted and try and implement it in a more robust fashion. If this is a school assignment, most teachers will be happy to see a "better" solution than the one they're looking for. Just don't copy and paste the code I've provided and make sure you understand it.
Should rather be like below .. you need to test for the values of each variable and compound their output.
Considering you have your variable defined like below
string a = "No";
string b = "No";
string c = "No";
string d = "No";
You can check
if ((a == "No" ||b == "No" ||c == "No" ||d == "No" )
You can as well use All() method from System.Linq
if((new[] {a,b,c,d}).All(x => x == "No"))
First of all. Your code has some issues:
You cannot name variables just with numbers in C#. You could name them like, v1, v2, v3 etc.
since you want to compare boolean values why you are using string variables? Instead, you could declare your variables as follows: bool v1 = bool.Parse(reportCard.1.GetText());. Here you have to make sure that the string values which come from the object (reportCard) are suitable to boolean values. such as"True" or "False".
Then you can simply write the if statement as follows:
if (!v1 || !v2 || !v3 || !v4):
{
// do smth;
}

Compare multiple values in one condition [duplicate]

This question already has answers here:
Equality comparison between multiple variables
(14 answers)
Closed 7 years ago.
Int32 int1, int2, int3 = 123;
Given the above variables, how can I test that all of my variables have the value 123 without creating a collection to perform some Any or something on?
What I've Tried
if(int1 == int2 == int3 == 123)
{
// Fantastic code here
}
EDIT
I must apologise, I haven't been clear enough in my question. I'm fully aware of the && operator, I was asking with regard to 'elegance', i.e. how can I avoid repeating the value I want to compare against.
In the same way I have assigned all 3 integer variables the same value in one hit, I'd like to now make the comparison. It's looking as though there is no way of doing this, so far. I think I'm asking the impossible, I'll have to stick to the basic syntax and keep it simple.
You can create an usefull extension function:
public static bool EqualsAll<T>(this T val, params T[] values)
{
return values.All(v => v.Equals(val));
}
call it like:
bool res = 123.EqualsAll(int1,int2,int3);
You could try something like this, using the logical and operator:
if(int1 == 123 &&
int2 == 123 &&
int3 == 123)
{
}
if(int1 == 123 && int2 == 123 && int3 == 123) { // Code }
What your trying to achieve isn't possible the way you do it.
You have to separate it with &.
if(int1 == something && int2 == something && int3 == 123)
{
// Fantastic code here
}
This is how you should do it using && operator. You can check multiple conditions using this.
UPDATE :
As far as checking multiple values at one go is concerned, you can try making an array out those values and just fire a simple LINQ statement like this to check all of them for a particular value :
if (new[] { int1, int2, int3 }.All(x => x == 1))
Dont know if this fits into your requirement, just a suggestion though.

is there any specific reason why you wouldn't use nested if statements? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is there a difference between using nested if statements and using one long if statement where there are a lot of arguments?
e.g.
if ( var1 == var2 && var3 == var4 )
{
//do something
}
or
if ( var1 == var2 )
{
if ( var3 == var4 )
{
//do something
}
}
I would like to know if there is any difference in doing things this way?
thanks
In general, the compiler will generate the same or nearly the same code for these two variants. For interpreted languages that support short-circuiting (not evaluating second part of an || or && when the outcome has been determined), it will also be pretty much the same thing.
My advice would be to use the form that represents what you want to do most clearly.
For example, if we want to check if two coordinates match:
if (x1 == x2 && y1 == y2)
Buf if your code is something like this:
if (country_of_origin == "Sweden")
{
if (today == thursday)
{
...
}
}
may make more sense...
The second style allows for checking that needs to be done independently of the first if condition.
For example, if you needed to do something in an extra condition where (var3 != var4) BUT (var1 == var2) still, it would be impossible to do with:
"if(var1 == var2 && var3 == var4)"
Thus, you would need something like:
if(var1 == var2){
if(var3 == var4){
}
//more code...
//... var3 & var 4 change...
//
if(var3 != var4){
}
}
As the commenter #Solace said, it simply allows for more flexibility.
They both do the same thing , but personally I think nested is neater and it also allows code to be executed on either side of the nested if, which is usually required
if ( var1 == var2 )
{
//do something here based on the first if but before second if
if ( var3 == var4 )
{
//do something
}
//do something here also which may be different based on the nested if result
}
But if you dont need this , then your first code is probably a tiny bit faster with just a single if
Different situations require different solutions:
if ( width == height && width == depth )
{
// Its a cube!
}
if ( x == y )
{
if ( p == q )
{
//do something for when x == y but p == q
} else {
//do something for when x == y but p != q
}
You cannot generalise for what constructs are should or should not be used - they are all appropriate in some situation.
Well, it depends what is your condition. If it's same as yours, than there is absolutely no need to choose the second way.
It's about writing clean and readable code - doing this like if (condition1 && condition2) you are suggesting that both conditions are absolutely necessary to the following fragment of code.

what is the point of using ternary operators instead of IF THEN? [closed]

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 11 years ago.
why make things more complex? why do this:
txtNumerator.Text =
txtNumerator.Text == "" ? "0" : txtNumerator.Text;
instead of this:
if txtNumerator.Text="" {txtNumerator.Text="0";}
Suppose you wanted to pass either zero or txtNumerator.Text to a method M. How would you do that?
You could say:
string argument;
if (txtNumerator.Text == "")
{
argument = "0";
}
else
{
argument = txtNumerator.Text;
}
M(argument);
Or you could say
M(txtNumerator.Text == "" ? "0" : txtNumerator.Text);
The latter is shorter and easier to read.
The larger point here is that statements are useful for their side effects and expressions are useful for their values. If what you want to do is control which of two side effects happens, then use an "if" statement. If what you want to do is control which value gets chosen from two possibilities, then consider using a conditional expression.
UPDATE:
Jenny asks why not just do this?
if (txtNumerator.Text == "")
{
M("0");
}
else
{
M(txtNumerator.Text);
}
That's fine if there's just one condition to check. But what if there are, say, four? Now there are sixteen possibilities and writing the "if" statement for it gets messy to say the least:
if (text1.Text == "")
{
if (text2.Text == "")
{
if (text3.Text == "")
{
if (text4.Text == "")
{
M("1", "2", "3", "4");
}
else
{
M("1", "2", "3", text4.Text);
}
}
else
{
if (text4.Text == "")
{
M("1", "2", text3.Text, "4");
}
else
{
M("1", "2", text3.Text, text4.Text);
}
}
... about fifty more lines of this.
Instead, you can just say:
M(Text1.Text == "" ? "1" : Text1.Text,
Text2.Text == "" ? "2" : Text2.Text,
Text3.Text == "" ? "3" : Text3.Text,
Text4.Text == "" ? "4" : Text4.Text);
It's one expression, so you can use the result directly in an assignment or a function call without having to duplicate the context in which you're using it. That makes a lot of usage scenarios significantly cleaner to write and read. For example:
int abs = (x >= 0) ? x : -x;
versus
int abs;
if (x >= 0)
abs = x;
else
abs = -x;
There are many standards guides that say not to use the ternary operator. However you could agre that all language feature are unnecessary except for goto and if. I use it when having a multitude of if then elses.
It makes the code more readable in some people opinion, a lot of constructs in the language are syntactic sugar (think about do..while, while..do, and for(..)) and in the end of the day you choose whatever works for you (and your team).
I for example think that the above code should be implemented with an extension method:
txtNumerator.SetDefault("0");
If you go with the if-then construct, you end up with two assignments to the same variable, in two separate blocks. The ternary form has only one assignment. So there is no need to look at a second block to verify to yourself what both blocks are performing an assignment to the same variable. In that respect I think the ternary form reads better.
On the other hand if C# worked like Ruby and if was an expression, then you could do without the ternary operator and use if-else in that case:
txtNumerator.Text = if (txtNumerator.Text == "" ) "0"; else (txtNumerator.Text);
which I would prefer because then the different syntax of ?: could be dropped.

How can I reorder sub-expressions in Visual Studio?

I would like to re-order sub expressions in an if statement. Here is an example:
Input:
if ((a == 1) || (a == 3) || (a == 2))
{
}
Desired output:
if ((a == 1) || (a == 2) || (a == 3))
{
}
Is there any tool that can automatically reorder these sub expressions?
Or the following identical code:
Input:
switch (a)
{
case: 1;
case: 3:
case: 2;
break;
}
Desired output:
switch (a)
{
case: 1;
case: 2:
case: 3;
break;
}
Clarification:
My question does not address short circuiting. This is a useful discussion, and as Reed pointed out re-ordering parameters in most cases is dangerous.
I was just curious if parsing tools such as ReSharper or Code Rush have this functionality. These tools probably create an AST to preform their refactoring and for them to reorder sub-expressions would not be too difficult.
I don't know of a tool that would automatically do this, at least in the "if" statement case.
In general, it would be bad if a tool did this automatically. The following two statements behave differently:
if ((a == 1) && (b == 3) && (c == 2))
and
if ((a == 1) && (c == 2) && (b == 3))
In the first case, if b != 3, but a == 1, it will check a, then check b, then skip the block.
In the second case, it would check a, then check c, then check b. You'd lose the ability to short-circuit the checks.
Granted, in most cases, this doesn't matter, but when you're using methods instead of values for a/b/c, it can be expensive.
Edit: I see that you've updated to use OR instead of AND. The same issue exists with OR, except that the short circuit will happen when the first condition is true, instead of when the first condition is false.
I agree with Reed Copsey's answer. However, since no one has mentioned it yet:
Depending on the language that you use, the switch statement doesn't behave the same as if/elsif/else. I know that for C, Java, etc. they use branch tables to determine what should be executed. (Not sure about something like PHP.) It's mentioned on the Wikipedia article, if you'd like to read more.

Categories

Resources