Where and how to use && Operators - c#

I have this piece of code which i simplified from my app. It does what I want but I know its not put in the most efficient way because I'm still having some trouble understanding the && and & operators.
if (AgeInput.Text.Equals(""))
{
Textblock1.Text = "✘";
}
else if (AgeInput.Text.All(Char.IsNumber)){
Textblock1.Text = "✔";
//DO-THIS-A
}
else
{
Textblock1.Text = "✘";
}
I need it to make sure there is no white spaces in the string and to also check so its not empty and finally check if its a number, If it ticks all those requirements it will //DO-THIS-A
Whats the most efficient way to do this?
EDIT:
If somebody knows how to make a XAML textbox numerical only (so no whitespaces) that would be even better (only a single property or don't worry otherwise)

if(!String.IsNullOrEmpty(AgeInput.Text) && AgeInput.Text.All(char.IsNumber))
Textblock1.Text = "✔";
else
Textblock1.Text = "✘";
String.IsNullOrEmpty returns true if the input is as stated: Null or Empty.
We Invert that with the "!", so that it returns true if it isn't empty.
Then we add the && Operator to expand the if condition and ask if the text only contains numbers.
Also look here: For a description of the difference between &, && and |, ||

Not really sure I understand your question, because && and & are for totally different uses.
if (string.IsNullOrWhiteSpace(AgeInput.Text))
{
Textblock1.Text = "✘";
}
else if(Char.IsNumber(AgeInput.Text.All))
{
Textblock1.Text = "✔";
}
The & is a binary operator and && is a logical operator.

Related

What does the bracket in this expression mean

I am modifying another developer's code and I don't know what the [0] bracket following the string means in this context, can someone explain to me? My first thought is it is referring to the first column of GridView1 but that isn't the correct way to designate a column is it? BTW the string values in the if statement are 7 digit numbers expressed as strings. The first column is the DataKey column.
if (GridView1.SelectedValue.ToString()[0] != '5' && GridView1.SelectedValue.ToString().Substring(0, 2) != "95")
{
LinkButton1.Visible = false;
LinkButton2.Visible = false;
}
else
{
LinkButton1.Visible = true;
LinkButton2.Visible = true;
}
String Accessing Individual Characters
You can use array notation with an index value to acquire read-only
access to individual characters
if (GridView1.SelectedValue.ToString()[0] != '5' && GridView1.SelectedValue.ToString().Substring(0, 2) != "95")
As noted in the comments, both the below will throw if there are not enough characters
GridView1.SelectedValue.ToString()[0]
GridView1.SelectedValue.ToString().Substring(0, 2)
Also as per DRY calling this twice is redundant and also messy
GridView1.SelectedValue.ToString()
When you can
var something = GridView1.SelectedValue.ToString();
Lastly, normally you would check this for sanity sake, Like
if(!string.IsNullOrEmpty(something) && something.Length >= 2)
if (something[0] != '5' && something.Substring(0, 2) != "95")
Anyway, have fun stringing

Best way to check several conditions on a Textbox.Text

I'm done with my current project and currently trying to improve the code itself.
In the app I developped, when the user clicks the "print" button, the different text in the textboxes are verified for things like is it null or empty ? is it numeric ?
My problem is that I end up with monster lines of code like
if (!String.IsNullOrEmpty(textBoxNbPieces.Text) && !String.IsNullOrEmpty(textBoxNbLotTrempe.Text) && !int.TryParse(textBoxNbPieces.Text, out numero) && !int.TryParse(textBoxNbLotTrempe.Text, out numero))
{
if (int.Parse(textBoxNbPieces.Text) < int.Parse(textBoxNbLotTrempe.Text))
{
erreur++;
}
}
How could I avoid that ?
You dont need to check IsNullOrEmpty and also int.TryParse, the latter includes the former.
bool valid = int.TryParse(textBoxNbPieces.Text, out int pieces)
&& int.TryParse(textBoxNbLotTrempe.Text, out int trempe)
&& pieces >= trempe;
if(!valid) erreur++;
[disclaimer: C#7 syntax]

c# using indexofany for the decimal point and restricting only to one decimal point

`private void Dot_Click_1(object sender, EventArgs e)
{
if (NumBox1.Text.IndexOfAny(char['.'])
{
}`
I think the solution for the restriction of one decimal point is here.
if (!string.IsNullOrEmpty(NumBox1.Text)
{
numbox1.text = "0" + ".";
}
}
this is when the textbox is empty. Then I clicked dot sign to get automatically a result of "0." inside the textbox. But, it only returns "."
It's not clear why you've got char['.'] at all, or what you expect it to mean. I suspect you just want the character literal '.' and use IndexOf.
else if (NumBox1.Text.IndexOf('.') == -1 && ...)
You only want to use IndexOfAny if you're looking for multiple things, in which case you'd want something like:
IndexOfAny(new[] { '.', ',' })
Or even more simply:
else if (!NumBox1.Text.Contains(".") && ...)
I strongly suspect that your conditions really aren't what you want - basically at the moment you'll always set the textbox value to "0." if you don't have a dot (ignoring any previous input), and NumBox1.Text will never be null - but you need to work through that for yourself.
EDIT: Using a single call to IndexOf isn't going to tell you if there's more than one occurrence of .. One simple way to do that is:
if (text.IndexOf('.') != text.LastIndexOf('.'))
{
...
}

Compare strings in if statement

Trying to write a piece of code to compare two strings. If either are equal to the textbox then it opens a new winform. I know how to do the winform part.
string CreditCard1 = "Some numbers";
string CreditCard2 = "Some Numbers";
string RFIDCard1 = "E00700000330E44C";
string RFIDCard2 = "E00700000338E539";
if(CardScan_txtBx = CreditCard1 || RFIDCard1)`
I get an error from MSVS 2010 saying:
Operator '||' cannot be applied to operands of type 'string' and 'string'
Is there a way to do what I want?
This line is the culprit:
if(CardScan_txtBx = CreditCard1 || RFIDCard1)`
Try:
if(CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1)
On a side note, it scares me that you're apparently working with credit card information, but don't know how to compare values in a text box. I really, really hope, for the sake of your customers, that you plan on investigating how to securely manage that information.
There are three problems here:
You cannot compare against multiple values using an OR (||). This is a surprisingly common misconception, but makes no sense to the compiler.
Comparison in C# is done with ==. = is for assignment.
A TextBox is not a string; you need to use its Text property to get or set the text it contains.
So in the end, your if statement should look like this:
if(CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1) {
// ...
}
Ok you have 2 issues here, firstly single equals is assignment not comparison and secondly each argument separated by an or needs to be a bool, ie should be
if(CardScan_txtBx == CreditCard1 ||CardScan_txtBx == RFIDCard1)
Could you use else if?
if(CardScan_txtBx == CreditCard1)
{
//Do something
} else if(CardScan_txtBx == RFIDCard1)
{
//Do something
}
The other answers have the correct code, here is an explanation of the why. When you use the || operator, it is expecting an expression on either side to be something that evaluates to a bool (true or false). When you wrote CardScan_txtBx.Text == CreditCard1 || RFIDCard1 you have an statement that evaluates to a bool on the left, CardScan_txtBx.Text == CreditCard1 and you have a statement that evaluates to string on right RFIDCard1 Because a string is not a bool, you get the compile time error. that is why you must repeat the == operator on the right hand side so that you say CardScan_txtBx.Text == RFIDCard1
Try out with following code.....
if (CardScan_txtBx.Equals(CreditCard1) || CardScan_txtBx.Equals(RFIDCard1))
{
//Code
}
Try this:
if (CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1)
See here: http://msdn.microsoft.com/en-us/library/53k8ybth%28v=vs.71%29.aspx
Not: =
Right: expr1 == expr2
You can also use a List.
List<string> listOfValidStrings = new List<string>();
//Initialise all valid strings.
if(listOfValidStrings.contains(txtbox.text())
{ do something.}

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