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]
Related
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
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.
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.
Suppose I have a long, complex list of conditions, which must be true in order for an if statement to run.
if(this == that && foo != bar && foo != that && pins != needles && apples != oranges)
{
DoSomethingInteresting();
}
Typically, if I'm forced into doing something like this, I'll just put each statement on its own line, like this:
if
(
this == that
&& foo != bar
&& foo != that
&& pins != needles
&& apples != oranges
)
{
DoSomethingInteresting();
}
But I still feel this is a bit of a mess. I'm tempted to refactor the contents of the if statement into its own property like this
if(canDoSomethingInteresting)
{
DoSomethingInteresting();
}
But then that just moves all the mess into canDoSomethingInteresting() and doesn't really fix the problem.
As I said, my goto solution is the middle one, because it doesn't obfuscate the logic like the last one and is more readable than the first. But there must be a better way!
Example in response to Sylon's comment
bool canDoSomethingInteresting
{
get{
//If these were real values, we could be more descriptive ;)
bool thisIsThat = this == that;
bool fooIsntBar = foo != bar;
bool fooIsntThat = foo != that;
return
(
thisIsThat
&& fooIsntBar
&& fooIsntThat
);
}
}
if(canDoSomethingInteresting)
{
DoSomethingInteresting();
}
In my opinion moving the mess into a Property or a Method is not that bad an idea. That way it is self contained and your main logic where you do the if(..) check becomes more readable. Especially if the list of conditions to check is huge, it is better off being in a property, that way if you need to re-use that you are not duplicating that check.
if(IsAllowed)
{
DoSomethingInteresting();
}
Containing the code for the different conditions in separate vars is a great way to go for readability and maintainability. When your vars are named good you get
if (goToNextPage)
{
if (notAdmin)
{
RedirectToNormalPage();
}
else
{
RedirectToAdminPage();
}
}
Compared to something like this
if ((x == 1) && ((y == 'r') || (y == 't')))
{
if (!a)
{
RedirectToNormalPage();
}
else
{
RedirectToAdminPage();
}
}
I will let you choose which one you would want to read when you go back to your code at a later date.
Method is good. Better method name would tell what it tests, not what can be done if it is true. Like
if (isFooValid()) { mergeFoo(); }
If it fits logically to the code flow and especially if I don't care if it is done or not at that point, I also often wrap whole if to a method:
maybeMergeFoo();
The key is to mentally step back and look what fits best to the current code, and to the code you are going to write next. Often it is then clear what is the right way to organize the code.
I want to check if two string are of the same length. I tried the following, but it doesn't work.
string passnew = "1233";
string passcnfrm = "1234";
if((passnew.Length&&passcnfrm.Length)>6 ||(passnew.Length&&passcnfrm.Length)<15)
{
// ...
}
Why does it not work? What do I need to change?
if(passnew.Length == passcnfrm.Length &&
passnew.Length > 6 && passnew.Length < 15)
{
// do stuff
}
You are missing some basic syntax lessons. What you write inside of these brackets are conditions. We have unary operators (operating on one thing), binary operators (two) and one tertiary operator (forget about that one).
You cannot construct something like your "boundary test" with those easily.
A possible way:
(passnew.Length > 6) && (passcnfrm.Length > 6)
But you aren't testing if the length is equal anyway, even if you could use a syntax like that. You seem to want to compare if both are longer than 6 chars and shorter than 15 chars. One at 7 and one at 14 would satisfy both conditions..
if(passnew.Length == passcnfrm.Length &&
(passnew.Length < 15 && passnew.Length > 6))
{
// ...
}
Checks both are same length, and either one is more than 6 and less than 15 characters long.
that would be:
if(passcnfrm.Length.Equals(passnew.Length))
{
//do stuff
}
A probably better way to do it is:
if (( passnew != null && passcnfrm != null )
( passnew == passcnfrm )
&& ( passnew.Length > 6 && passnew.Length < 15 ))
{
// do stuff
}
Hides the length check inside the equality check which you'll probably need, it isn't in your question but the variable names make it pretty clear you're doing a password change function there. I added the null check to make sure the length checks don't throw a NullReferenceException, not needed in the example because you assign both manually, but might save some trouble if you're going to convert this to a method later on.
You can use like this:
if (s.Contains(s1[i]))
or:
boolean equalsIgnoreCase(String anotherString);
or use this method:
public static int occurrence(string [] a, string a2)
{
int occ = 0;
for (int i = 0; i < a.Length;i++ )
{
if(a[i].Equals(a2))
{
occ++;
}
}
return occ;
}