I want to perform an AND operation. My inputs are 2 objects. It could be a string like "true" or it could be an expression like "1==1" as well. When using && operator, am getting an exception that String was not recognized as a valid boolean.
Please help me.
return Convert.ToBoolean(obj[0]) && Convert.ToBoolean(obj[1]);
Sorry for the earlier post which was not clear enough.
Converting "1==1" to a boolean is not possible for the Convert.ToBoolean method. It just converts the strings true and false.
You will have to either write a expression evaluator yourself, or use some kind of library to parse your string to a boolean (like Flee for example)
First make sure obj[0], obj[1] will only contain 1 or 0(char or integer).
Because Convert.ToBoolean does not understand anything other than 1 or 0.
The below one will work
Convert.ToBoolean(true) && Convert.ToBoolean(1==1)
Why use a string?
The conversion will not evaluate code, it will check if the supplied data is possible to convert to a bool and do so if possible.
Your function will always return true if it was working, cause 1 is always equal to 1, and true is always true.
This is nearly impossible as C# is strongly type language.
What you trying to do is for weakly types languages like JS. "1==1" will work for JS, not for C#.
Remove quotes in order to make it work(You might as well remove first operand, as it doesn't make any sense):
return ( 1 == 1 );
Related
I am trying to test and see if 4 user inputted answers are correct(I have tested without using if statements and all variables are correct), however it seems to only be checking 1 out of the 4 conditions in the if statement. I tried using both the single & and double && operator, and neither made a difference?
if(isOneCorrect.ToUpper() == checkBox1.Checked.ToString().ToUpper() &&
isTwoCorrect.ToUpper() == checkBox2.Checked.ToString().ToUpper() &&
isThreeCorrect.ToUpper() == checkBox3.Checked.ToString().ToUpper() &&
isFourCorrect.ToUpper() == checkBox4.Checked.ToString().ToUpper())
{
MessageBox.Show("you won!");
}
What can I do to make the if statement make sure EVERY condition of the 4 is correct?
The boolean operators/expressions in C# shortcut - this means if you have several sequential boolean operators (like you have) then expression evaluation will stop when the overall result can no longer be changed.
So, to explain that a little more: you have four && operators. For the if statement to valuate to true all of those ANDed expressions need to evaluate to true. If the first one fails there is no point evaluating the rest, the final result will not change.
When comparing strings you should use the string.Equals() extension method.
However you did state in the comments that isOneCorrect is boolean; if checkBox1.Checked is also boolean then you do not need to convert anything to string, just compare the two booleans. If checkBox1.Checked is a nullable bool (bool?) then use the HasValue and Value properties to access it as a bool.
This is just a wondering question for the c# language. I have checked in the MSDN operators and can't see anything close.
When I use LINQ to XML to retrieve some elements, I am passing some lambda expressions in WHERE methods to select specific elements.
But I can see that I am using the following statement which annoys me a bit.
bool myCondition;
// some codes
var elements = xDocument.Descendants("items").
Where(x=>x.Attribute("id")!=null&&
(myCondition)x.Element("blah").Value=="blah":
x.Element("blah").Value!="blah").ToList();
But somehow I keep writing to code as below(no idea why :)):
// some codes
var elements = xDocument.Descendants("items").
Where(x=>x.Attribute("id")!=null&&
x.Element("blah").Value?myCondition="blah").ToList();
I kind of see the boolean myCondition as !(exclamation mark) or =(equal sign).
if true then = if false then !.
I just wonder would that be any possibility in the future to add these types of operators? or there are some better operators that would shorten my condition?
Would this work with any other programming language out there? maybe javascript?
and if you are downgrading then please tell why.
You can already express that condition in C# without conditional operator:
myCondition?
xDocument.Element("item").Value=="blah":
xDocument.Element("item").Value!="blah"
is the same as:
myCondition == (xDocument.Element("item").Value == "blah")
Whether it is more readable is open question. You may consider having helper method with good name instead.
I was reading the MSDN article of the boolean structure, when I saw that a boolean has two fields: TrueString and FalseString. These respectively return "True" and "False".
After some searching, the only example I could find is in this dotnetperls article. The article states:
Programs often need these strings. TrueString and FalseString are a useful pair of readonly members. They represent truth values in string format. They provide indirection and abstraction over directly using string literals.
So appearantly it's useful for some situations. But the same article fails to provide a realistic example (IMHO anyway).
Some further reading also brought this to my attention: TrueString and FalseString are public static readonly fields. And this dornetperls article states:
The language specification recommends using public static readonly fields ... when the field is subject to change in the future.
Now this I can somewhat understand. If the .NET developers ever decide to change "True" and "False" to respectively "OkeyDokey" and "Negatory", it's smart to use TrueString and or FalseString.
But that still leaves me with the question: in what kind of scenario do you want to compare a string with the string literal of a boolean? Because appearantly: "Programs often need" them.
For the same reason that string.Empty exists. Some people prefer a semantically named value in code over a literal one.
In modern .NET (anything after .NET Framework) the following code prints True three times:
Console.WriteLine(ReferenceEquals("True", bool.TrueString));
Console.WriteLine(ReferenceEquals("False", bool.FalseString));
Console.WriteLine(ReferenceEquals("", string.Empty));
This tells us there is zero runtime difference between the literals and the fields. They are exactly the same object at runtime.
Try this for yourself on sharplab.io here.
Others have mentioned using it to compare with when parsing boolean strings, but I would not recommend that. If you want to convert a string to a bool, use bool.TryParse or bool.Parse. Using == does a case-sensitive comparison, which is probably not what you want. Furthermore, the framework's methods are optimised specifically for common cases. You can see these optimisations in the code on GitHub here: https://github.com/dotnet/runtime/blob/f8fa9f6d1554e8db291187dd7b2847162703381e/src/libraries/System.Private.CoreLib/src/System/Boolean.cs#L226
If the program stores data in a human readable file or database, it may need to store values as strings. When you read the data back in, if you know the data was written by your application and uses a standard string representation, you can compare x == bool.TrueString faster than you can bool.TryParse(x ...). You could also validate the data by making sure all values x == bool.TrueString || x == bool.FalseString
If the data was typed by humans, or a different system, TryParse is a better option, as it accepts more values as true and differentiates between a definite false and an invalid input. (MSDN Boolean TryParse)
In easy words. Boolean is a Structure. this boolean expose ToString() method which represent a human readable text for the users. So if you write some thing like.
bool b = false;
b.ToString();
the output will be the "False" insteed of 0. the "False" is readable by human and easyly being captured.
Also some where you may want to parse a text value to a boolean value. so these also can be represented as boolean values. for example. we use
Boolean.TryParse("false" ,out mybool)
the false value is being set by the Tryparse method as this finds that we can read values from strings tool.
It can be used as a default value for missing "stringly-typed" configuration parameters. Here's a concrete example I've recently used:
if (bool.Parse(ConfigurationManager.AppSettings["IsTestMode"] ?? bool.FalseString)) ...
...which is - in my humble opinion - simpler and more readable than
var isTestModeString = ConfigurationManager.AppSettings["IsTestMode"];
if (isTestModeString != null && bool.Parse(isTestModeString)) ...
(I deliberately do not use TryParse here, since I do not want to silently ignore invalid values. I want an exception to be thrown, if the configuration value is present and something other than True or False.)
There are many situations where you may need to compare if a string is equal to "True", such as checking an API response. Note: it's more efficient to compare strings but often safer to parse.
The only advantage to using the built-in properties is you won't make typos (assuming you have Intellisense) and you don't have to remember the casing (e.g. "true" instead of "True).
I am using C#, .NET 3.5. I have following code
string.Compare("KHA","KTB",true)
It returned value 1. This means KHA > KTB in alphabet order.
I expect it returns value -1.
Can anyone help me fix this?
Yes, all of you are right. It's because of the Culture. I add CultureInfo.InvariantCulture and it is solved.
Thanks all!
strig.Compare returns the relative position in the sort order. Since 'H' comes before 'T' that is why you are getting 1
Its should return -1, See the image
There must be something wrong going on with your compiler, it should return -1 and your understanding for the string.Compare is right.
You may try using CultureInfo.InvariantCulture:
int value = string.Compare("KHA", "KTB", true,CultureInfo.InvariantCulture);
The call string.Compare("KHA","KTB",true) should return -1 as expected. It does when I test it.
If you get any other result, you either are using other strings, or you have a default culture where 'T' is actually considered to come before 'H'.
For the latter case, you can specify a culture info in the call:
string.Compare("KHA", "KHB", true, CultureInfo.InvariantCulture)
If you are really getting 1 against string.Compare("KHA","KTB",true) then your system's current culture must be making an effect. Check the documentation of String.Compare. Also check the best practices of comparing a string here.
I am try to control multiple strings variables is empty or not at once:
My first approach is very simple:
if(string.isNullOrEmpty(val1) && string.isNullOrEmpty(val2) && string.isNullOrEmpty(val3))
My second way looks like this
if(string.isNullOrEmpty(val1 + val2 + val3))
Which one is fastest and elegant?
Is there any options to do this operation?
The first was faster in my test (just had to): 6ms vs. 70ms and that was on 10,000,000 iterations each (so the speed difference probably doesn't matter very much unless you're doing this on a massive scale).
Anyway, i find the first to be more clear.
Also it doesn't rely on behavior of IsNullOrEmpty that is not immediately obvious (you might just as well think that passing null parameters causes an ArgumentNullException if you don't know better), which i think is important.
Note: The test was with all variables set to null, but setting them to other values confirms it, the longer the strings get, the longer option 2 takes, while option 1 stays at about 30ms max.
Also, the first returns true if any of the strings is null or empty, while the second does it only if all of them are null or empty. So it's not the same check.
They are not equivalent. The first one checks if any of them is null. The second one checks if all of them are null. Make up your mind.
How about this?
new string[] {val1, val2, val2}.All(s => string.IsNullOrEmpty(s))
Or something similar.
I would expect 'fastest' to depend on how often you expect one or more of the strings to actually be null or empty.
For example, if val1 is often going to be null or empty then the first option is likely to be best; if they are all rarely going to be null or empty then I'm not sure of the answer, but it can't take more than five minutes to knock together a few benchmarks for your particular expectations.
(Also, note that the two options don't do the same thing, the first is true if ANY of them are null or empty the second is not doing that)
if(string.isNullOrEmpty(val1 + val2 + val3)) seems to me the fastest
I would advice you to also use concat
but behind the scenes it uses the '+' operator.
I think this is the fastest.
If it werent nullable I suggest summing their length and check ==0
The second one:
if(string.isNullOrEmpty(val1 + val2 + val3))
equals
if(string.isNullOrEmpty(val1) && string.isNullOrEmpty(val2) && string.isNullOrEmpty(val3))
(note the && instead of ||)
but will create an intermediate string, whereas my second version will not create extra strings and stop checking as soon as one string is not empty.
If you have a number of string variables, then I think it is more readable to use the first construction:
if(string.isNullOrEmpty(val1) &&
string.isNullOrEmpty(val2) &&
string.isNullOrEmpty(val3))
{
}
This way, it seems like each variable is treated separately, and this code is a little easier to change if you need to treat one of the variables in another way.
But in case all of the string variables are to be treated in the same way, they are very likely to be represented as an array or another kind of enumeration. Then it's definitely better to use John M Gant's suggestion:
if(myStrings.All(s => string.IsNullOrEmpty(s)))
{
}