This question already has answers here:
Multiple string comparison with C#
(8 answers)
Operator || cannot be applied to type bool and string / string and string
(6 answers)
Closed 2 years ago.
I am starting out with C# and I think I understand && and || when they are used as bool, but I was wondering how to use them in a text string like this:
if (label1.Text == "Its Hot outside" || "Its warm outside")
{
//picture of a sun
picturebox.Show();
}
When I try something like this it gives me
Operator '||' cannot be applied to operands of type 'bool' and 'string'
The && works fine here, but how would I apply an "or" condition?
Since you are learning, I will take a little time to try and explain in a very basic way. If you don't understand, ask questions till you do. Best way to learn!!!
Now, its not a good idea to write code that way. the idea is to check if label1.Text is equal to "Its Hot outside" OR label1.Text is equal to "Its warm outside".
In regular English expression you can say it as it is but in programming, computers are not that smart(FACT), they need everything to be told them in clear language. this is called logics.
With this, a better logic to do this is;
if (label1.Text == "Its Hot outside" || label1.Text == "Its warm outside")
{
//picture of a sun
picturebox.Show();
}
What you have initially done is saying
If label1.Text is equal to the string "Its Hot outside" OR if "Its warm outside". the last part is not evaluated as a boolean, it's a string, which is the cause for the exception message: "Operator || cannot be applied to operands of type bool and string". Both operands must be boolean types.
What I have done is saying;
If label1.Text is equal to the string "Its Hot outside"
OR
If label1.Text is equal to the string "Its warm outside"
So it checks label1.Text against each string provided.
And this is really how to build logics for a computer.
This link could do you some good: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/
Related
This question already has answers here:
if statements matching multiple values
(16 answers)
Closed 12 days ago.
I have written a simple conditional statement, in which I'm getting a string input from the user, checking if it's equal to something but the nature of my code makes me add a single more operand to operate between
I tried this but it gives an error that you can't operate between two strings, obv there is some logical fallacy but I want a similar solution to this problem
if (Console.ReadLine() == ("s"||"S"))
Now I know this works if I make a separate variable and just check with it for both "S" and "s", but I want to do it inline and within that single statement, If I add another "Readline()" it will just take two inputs and won't do what I want it to do.
If there is anyway to make this work within that line, please let me know.
You have to declare the variable outside the condition, but you can do everything else in one line.
You can use is to make it slightly more readable (but only works for literal comparison).
string input;
if ((input = Console.ReadLine()) is "s" or "S")
Or if you have to use == then
string input;
if ((input = Console.ReadLine()) == "s" || input == "S")
Would I suggest doing this? No. Do the sane thing by not cramming all this logic in one line.
string input = Console.ReadLine();
if (input is "s" or "S")
What about trying
if (Console.ReadLine().ToLower() == "s")
Hey I have been using bencodeNET for a while and it works great with one file torrents but when it comes to multiple file torrents it stores the filenames in a list, this shouldn't be a problem but it seems to be.
dosent matter how I try to read from the list I always end up with a error
string search = "5";
string result = torrent.Files.Single(se => se == search);
Operator '==' cannot be applied to operands of type 'TorrentFile.TorrentFileFileEntry' and 'string'
https://github.com/Krusen/BencodeNET/blob/master/BencodeNET/Torrents/TorrentMultiFileInfo.cs
I do feel that the answer is here but cant figure it out how it should be implemented, thanks for any help
se is an object of type TorrentFileFileEntry, which you are trying to compare to a string - this won't work as they are objects of different types.
Perhaps you should be searching a property of se, e.g. se => se.FileName == search.
I'm guessing the property name here.
I was creating an averaging program in C# just to make sure I got array's.
What I'm trying to do is ask the user if they want to average whole numbers, or non whole numbers. I thought an If statement would be appropriate.
But the problem is, I dont know what operator to use for MULTIPLE conditions, I think this is best explained by seeing the code. (Even I'm getting confused now D:)
Console.WriteLine("\n Do you want to average whole numbers, or non-whole numbers? \n");
if (Console.ReadLine() == "whole numbers" && Console.ReadLine() == "Whole numbers")
{
Console.WriteLine("You chose whole numbers.");
}
My confusion occurs at the "Condition" && "Condition2" bit. I don't know if && is the correct operator, and C# certainly doesn't think so!
I've looked across the C# MSDN Operator list, but couldn't really understand which one to use...
P.S: The whole reason I'm doing the multiple conditions is because of capital letters ETC, if any of you knew how to combat that with a way to disregard caps and other error prone user ticks, then please tell me :D
Console.ReadLine reads input from the console. When the user presses enter, it returns a string. In your code it will ask twice from user to enter something if the first condition was true. So, the other one is redundant.Because you have used && operator, which is conditional AND operator, but you must use conditional OR statement(||). So, you have two choice:
Either assign Console.Readline() result to some variable and use this inside if statement, but change && to ||.
Or use string.Equals(String, String, StringComparison) overload, to find if two strings are equal case-insensitively
In first case, you can check as many conditions as you can. But of course these are redundant. You can compare entered string with whole numbers case insensitively with the second approach:
if (string.Equals(Console.ReadLine(), "whole numbers", StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("You chose whole numbers.");
}
Rather than testing for every variation in capitalization, maybe consider using the String.ToLower() method to convert the string for comparison to lowercase. Basically, by calling this method, the string that you use to call the method is converted to all lowercase letters. By using this, you make your program less prone to failure by means of capitalization.
Example:
string UserDecision = (Console.ReadLine()).ToLower();
if(UserDecision == "whole numbers")
{ // perform task }
In my example, I used Console.ReadLine() to get the user's input and then I immediately converted it to lowercase before storing it into the variable. This makes it much easier to compare strings.
In the case of which operator to use:
|| is the OR operator (ONLY ONE condition must be true)
&& is the AND operator (BOTH conditions must be true)
I am trying to use regular expressions with my C# code, and I can find a few examples here on what those regular expressions might look like for my cause, but nowhere can I tell how I am supposed to (syntactically) implement that into my logic and code.
I have tried setting up an external .cs file and then calling the method, but the value returned is unable to be casted or worked with in any way.
The code can be found here:Checking strings for a strong enough password
In any event, I just want to know how I can check (and test against) values in a password to make sure it is up to standards that I specify.
A better way than suggesting to use regular expressions (since information on how to incorporate them into my own specific logistical setup is both very sparse and very confusing)
...is suggesting how it can be done without them.
I know I could use
foreach(char c in myString)
and then test individually, character by character, but I was hoping there was a better way that can either be regex, explained (that is, explained how to call this suggestion into action, not just posting a string of seemingly (but not) random characters and told, hey use that!), or not using regex at all, but somekind of shorthand, perhaps.
Truth is I would use regular expressions, but every time I look them up I can't seem to find anything that is useable by me in WebMatrix.
I want to be able to test a password to be sure that it has both an uppercase and a lowercase number. In addition I need to check for at least one number.
UPDATE:
Okay, allow me to rephrase my question, maybe I am being confusing...
How does regex work in webmatrix razor (C#). Please show how the regex actually works (I can't seem to find a clear, or even close to clear, answer on this on the web for webmatrix), then please show how it can be put (directly or indirectly) into if logic, on my cshtml page, so that I can actually check against it.
A Regular Expression (Regex), as you will find out, is a tool used in matching text against a pattern and even extracting or replacing matches in the source text.
To do this the Regex engine (which exists in the .Net framework inside the namespace System.Text.RegularExpressions) uses some established patterns that represent certain kinds of chars.
To use a Regex, you pass it the pattern agains which a text will be tested and the text itself.
For instance, the following snippet tests if there are lowercase letters in the text:
using System.Text.RegularExpressions;
...
var Pattern = "[a-z]";
if (Regex.IsMatch(SomeText, Pattern)) {
//... there is at least one lower case char in the text
}
The pattern used above estates that we are interested in a range of chars from lowercase "a" to lowercase "z".
A pattern to require at least one lowercase letter, one digit and one uppercase letter could probably be something like
#"[\d]+[a-z]+[A-Z]|[\d]+[A-Z]+[a-z]|[a-z]+[\d]+[A-Z]|[a-z]+[A-Z]+[\d]|[A-Z]+[\d]+[a-z]|[A-Z]+[a-z]+[\d]"
As you can see, a Regex pattern can be as simple as in the first example, but may escalate fast in complexity depending on the kind of information you want to check or extract.
In the Regex above, the items between square brackets are called character classes. The plus sign after an element is a quantifier, it indicates that the item may appear one or more times. Items separated by a vertical bar indicate alternatives. The "\d" pattern represents any digit from "0" to "9".
You don't really need a Regex to check the password strength in your application, but using then instead of the explicit tests you are currently making would (in my opinion), greatly improve your program's readability:
using System.Text.RegularExpressions;
...
if (!Regex.IsMatch(password, "[A-Z]")) {
errorMessage = "Your password must contain at least one uppercase character.";
} else if (!Regex.IsMatch(password, "[a-z]") {
errorMessage = "Your password must contain at least one lowercase character.";
} else if (! Regex.IsMatch(password, #"[\d]")){
errorMessage = "Your password must contain at least one numerical character.";
}
...
If you're trying to do this test on the page before the information is sent to the server, you can check with javascript and regex. I think this way is best, since you eliminate additional trips to the server. It can pass the javascript validation, post the data to your site, and you can validate more on the server (in case the user has javascript off). Razor syntax helps in the page rendering, but won't help you when the user is doing stuff on the page.
Pattern: ((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})
This is requiring at least 1 digit, 1 lowercase and 1 uppercase. It's also requiring the password to be between 8 and 15 characters long (inclusive). You can easily change the length requirements in the pattern. For example, if you wanted it to be at least 8 characters, but no max:
((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})
To use this in javascript (I did use jQuery to wire up my click event in my test and get the password from the input):
var password = $('#password').val();
var pattern = /((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})/;
var pass = pattern.test(password);
A Fiddle showing it in action: http://jsfiddle.net/gromer/chF4D/1/
Well I know this isn't the way to properly do this, (the proper way is using regular expressions, which is what I was attempting to figure out) but if you are like me, and sick of asking/searching the same question over and over again, without getting any entirely useful feedback, this is what worked for me.
int Ucount = 0;
int Lcount = 0;
int Ncount = 0;
foreach(char c in password)
{
if(c!='A' && c!='B' && c!='C' && c!='D' && c!='E' && c!='F' && c!='G' && c!='H' && c!='I' && c!='J' && c!='K' && c!='L' && c!='M' && c!='N' && c!='O' && c!='P' && c!='Q' && c!='R' && c!='S' && c!='T' && c!='U' && c!='V' && c!='W' && c!='X' && c!='Y' && c!='Z')
{
Ucount++;
if(Ucount >= password.Length)
{
errorMessage = "Your password must contain at least one uppercase character.";
}
}
if(c!='a' && c!='b' && c!='c' && c!='d' && c!='e' && c!='f' && c!='g' && c!='h' && c!='i' && c!='j' && c!='k' && c!='l' && c!='m' && c!='n' && c!='o' && c!='p' && c!='q' && c!='r' && c!='s' && c!='t' && c!='u' && c!='v' && c!='w' && c!='x' && c!='y' && c!='z')
{
Lcount++;
if(Lcount >= password.Length)
{
errorMessage = "Your password must contain at least one lowercase character.";
}
}
if(c!='0' && c!='1' && c!='2' && c!='3' && c!='4' && c!='5' && c!='6' && c!='7' && c!='8' && c!='9')
{
Ncount++;
if(Ncount >= password.Length)
{
errorMessage = "Your password must contain at least one numerical character.";
}
}
}
Again, please note that the proper way to do this is to use regular expressions, but this code works fine for me, and I got to end the wild goose chase that was understanding regular expressions.
UPDATE:
Or, if you want to do it right, read Branco Medeiros's post above, he posted after I posted this, and his way is the right way to do it (provided you don't want to do it with JavaScript before it is sent to the server. If your app is like mine and not resource intensive enough to need JavaScript to do this, use Branco Medeiros's example above).
I am attempting to validate a date text box to make sure the correct date format was entered.
I converted this vb6 code:
If (IsDate(txtBirthDate)) And (IsNumeric(Right(txtBirthDate, 4))))
into this C# code -
int output = 1;
DateTime output2;
if ((! DateTime.TryParse(txtBirthDate.Text, out output2)) & (!int.TryParse((txtBirthDate.Text.Substring(txtBirthDate.Text.Length - 5)), out output)))
{
MessageBox.Show("error")
}
What I am attempting to do is make sure that the last 4 digits of the date text box are numeric (the year - i.e 1990 in 05/10/1990) and if it is not a number, then show error. Although I cannot verify everything is numeric due to the "/" in the date format.
The code does not show an error and builds. But when I debug the application I receive an error. The error states:
Index and length must refer to a location within the string.
Parameter name: length.
Any ideas on how to accomplish this?
To check if a date is in a specific format, use DateTime.TryParseExact():
if (!DateTime.TryParseExact(output , "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out output2))
{
MessageBox.Show("error")
}
EDIT: Change the format according to your needs:
"d/M/yyyy" for UK and "M/d/yyyy" for US
Edit: It sounds like the cause of your error is your string is too short. Test the string length before you test the last 4 characters.
Three other issues:
The And operator in C# is &&. You are using & which is a bitwise operator.
To check the last four characters of the string, you should use .Length - 4, not 5.
You are negating the return values in your C#, but not in your VB. To match the VB, omit the !. But, it looks like that's not what you are actually trying to do. It looks like you want to show an error message if either the string is not parsable as a date or the year portion is not 4 digits. In that case use a an or comparison (||):
if (!DateTime.TryParse(txtBirthDate.Text, out output2) ||
txtBirthDate.Text.Length < 4 ||
!int.TryParse((txtBirthDate.Text.Substring(txtBirthDate.Text.Length - 4)), out output))
{
MessageBox.Show("error")
}
Keep in mind that yyyy/M/d is also parsable as a Date, contains a 4-digit year, but will fail your test. Is that what you want?
From the error provided it looks like you just need a length check to make sure you can process the code. You should also use && instead of & (or in this case probably ||) to ensure that the boolean expressions stop executing once a true state has been encountered.
if (txtBirthDate.Text.Length < 5 ||
(!DateTime.TryParse(txtBirthDate.Text, out output2) ||
!int.TryParse((txtBirthDate.Text.Substring(txtBirthDate.Text.Length - 5)), out output)))
{
MessageBox.Show("error")
}
However, this might be a good case for the use of a regular expression.
Regex reg = new Regex("^\d{2}/\d{2}/\d{4}$");
if (!reg.IsMatch(txtBirthDate.Text))
MessageBox.Show("error");
Tweaking of the regular expression to match fringe cases (leading zero's, alternate formats, etc) may be necessary.
int result;
if (int.TryParse(txtBirthDate.Text.Substring(test.LastIndexOf("/")), out result))
{
//its good
}
else
{
//its bad
}