Value is always true, even if false - c#

/*****For Local setup****/
var isLocal = _configuration.GetValue<bool>("IsLocalEvn");
if (isLocal)
return isLocal;
This is always returning true even if the value in appsettings is false
From appsettings.json
"IsLocalEvn": "false",

You can use the boolean type inside the JSON file.
"IsLocalEvn": false,
In your case, you are using a string value which is interpreted as true when it's converted to a boolean.

Related

Why elvis operator used in "if" statement is NOT a boolean algebra anymore?

This code below:
class B
{
public bool FinishedDownloading { get; set; } = false;
};
class A
{
public B DownloadStream { get; set; }
};
A a = new A();
Console.WriteLine(a.DownloadStream?.FinishedDownloading != false);
Console.WriteLine(a.DownloadStream?.FinishedDownloading == true);
Outputs:
True
False
How on earth a.DownloadStream?.FinishedDownloading != false is true when DownloadStream is null and FinishedDownloading is false?!
Let's forget about what happend and focus on the result.
We know this statement a.DownloadStream?.FinishedDownloading != false is true, because it's not false, so in our universe when something is true then it should be true, beacause 1 == 1, right?
So why when we do a.DownloadStream?.FinishedDownloading == true the result is now false?! Madness.
I think I kind of know what's going on here. It's because when DownloadStream is null then FinishedDownloading boolean value is not accessible, thus left side is null, so C# "thinks":
a.DownloadStream?.FinishedDownloading != false
Ok let's check if null value is not equal to boolean "false" value. Hmm, it certainly does not, so let's output true.
a.DownloadStream?.FinishedDownloading == true
Ok let's compare a null value with boolean "true" value. Hmm, that doesn't make any sense. It's not true, so let's output false.
Does anyone know if this is really the case? I find it very confusing and bug prone.
You're forgetting that Nullable<bool> (also known as bool?) and bool are two different types with a different list of possible values.
bool can either be true or false
bool? can be true, false or null
Since you've never initialized the DownloadStream property, it is therefore null. a.DownloadStream?.FinishedDownloading therefore returns a bool? with value null because ?. propagates the null.
And null != false is true since they are two completely different values.
If you initialize the DownloadStream property, e.g. by doing:
class A
{
public B DownloadStream { get; set; } = new B();
};
Then you will see that a.DownloadStream?.FinishedDownloading != false will return false, which is what you're expecting.

C# - How to skip parameters with default values?

Consider the following method example:
public void MyMethod (string par1, bool par2 = "true", string par3="")
{
}
Now let's say that I call MyMethod and set par3's value to "IamString".
How could I do that without setting par2's value to true or false?
I basically want to leave par2 value to its default.
I'm asking this because in Flash's ActionScript it is possible to do that by using the keyword default so I could call MyMethod ("somestring", default, "IamString") and par2 would be interpreted as true, which is its default value. I wonder if it is possible in C# as well.
public void MyMethod (string par1, bool par2 = "true", string par3=""){}
Myclass.MyMethod(par1:"par1", par3:"par3");
By the way, this won't work: bool par2 = "true"
string par2 = "true"
or
bool par2 = true
Talking about default values, you could also use this to get the default value for a particular type:
default(T)
You can specify this by name the parameter:
instance.MyMethod( "Hello", par3:"bla" );
Have a look here.
And there is another bug:
bool par2 = true
is correct..

Bool value always gets outputted to True only

I am having the following code snippet where I pass a value either True or False through the PropertyValue parameter in the method declaration.
public void SetTaskInstance(String PropertyName, String PropertyValue, int row)
{
bool bValue;
try
{
PropertyName = PropertyName.ToUpper();
switch (PropertyName)
{
case "BYPASSRULESENGINE":
m_tInstance.byPassRulesEngine =
System.Boolean.TryParse(PropertyValue.ToString(), out bValue);
break;
}
Console.WriteLine("Invoking method");
}
}
If I pass True, then True is outputted. However if I pass False, the parameter False is passed through the code but once the break statement is reached and when I hover my mouse over m_tInstance.ByPassRulesEngine, I see that the bool value has become True almost magically. Why is this happening ?
The return value of TryParse indicates if the parse was successful. And of course, the value "false" or "False" is valid, so TryParse would return true. The parsed value itself is written into the out bValue parameter.
Change the line
m_tInstance.byPassRulesEngine = System.Boolean.TryParse(PropertyValue.ToString(), out bValue);
to
bool parseSuccessful = System.Boolean.TryParse(PropertyValue.ToString(), out bValue);
if (parseSuccessful)
{
m_tInstance.byPassRulesEngine = bValue;
}
All TryParse methods behave that way. So read the documentation of TryParse on MSDN here:
http://msdn.microsoft.com/en-us/library/system.boolean.tryparse.aspx
Let me explain why you always receive a true value:
The function System.Boolean.TryParse returns true, if it can successfully do the conversion, from a String to a Boolean.
So in your example it will always be true.
Carsten Schütte has already given the solution code.
Look at msdn
the result of the conversion is stored in Output variable (your bValue)
When this method returns, if the conversion succeeded, contains true
if value is equivalent to Boolean.TrueString or false if value is
equivalent to FalseString. If the conversion failed, contains false.
The conversion fails if value is null or is not equivalent to the
value of either the TrueString or FalseString field.

Convert.ToBoolean("1") throws System.Format Exception in C#

Why does
Convert.ToBoolean("1")
throw a System.FormatException?
How should I proceed with this conversion?
Yes, this is as documented:
[throws] FormatException [if] value is not equal to TrueString or FalseString.
TrueString is "True" and FalseString is "False".
If you want to detect whether a string is "1" or not, use this code:
bool foo = text == "1";
Depends on what you want. Perhaps
var result = Convert.ToInt32(yourstirng) != 0
assuming any number but 0 is true. Otherwise a simple comparison would work.
var result = yourstirng == "1"
The parameter must be equal to either Boolean.TrueString or Boolean.FalseString. The values of these strings are "True" and "False", respectively. See MSDN.
The string value "1" is obviously not equal to "True" or "False".
The problem is, that youre giving a String here, not a number. It cant convert the String "1" to true, but the int 1.
Convert.ToBoolean(1);
should work.
When converting to Boolean it is best to use your own routine, where you handle all cases. .net Convert.ToBoolean isn't a practical routine, it is one of those function where you have to explain why it doesn't work.
I know this is old, but in case someone searches... simply do this:
Convert.ToBoolean(Convert.ToInt16("1")) works just fine. Not pretty, but needs be.
Another solution is to use an Extension Method on the string object. I used this technique in a case where I had to parse CSV files that had different strings that had to be converted to boolean values depending on their source and format.
public static class StringExtensions
{
public static bool ToBool(this string value,string trueValue)
{
if (value == trueValue)
{
return true;
}
else
{
return false;
}
}
}
This would be called like so...
MyProperty = CsvColumn[6].ToBool("1");
If you want, the truevalue parameter could be a string array if you needed to compare multiple values (like n/a, na, none) and you could add in false values if you want to further restrict it or use nullable types.

How do I safely cast a System.Object to a `bool` in C#?

I am extracting a bool value from a (non-generic, heterogeneous) collection.
The as operator may only be used with reference types, so it is not possible to do use as to try a safe-cast to bool:
// This does not work: "The as operator must be used with a reference type ('bool' is a value type)"
object rawValue = map.GetValue(key);
bool value = rawValue as bool;
Is there something similar that can be done to safely cast an object to a value type without possibility of an InvalidCastException if, for whatever reason, the value is not a boolean?
There are two options... with slightly surprising performance:
Redundant checking:
if (rawValue is bool)
{
bool x = (bool) rawValue;
...
}
Using a nullable type:
bool? x = rawValue as bool?;
if (x != null)
{
... // use x.Value
}
The surprising part is that the performance of the second form is much worse than the first.
In C# 7, you can use pattern matching for this:
if (rawValue is bool value)
{
// Use value here
}
Note that you still end up with value in scope (but not definitely assigned) after the if statement.
Like this:
if (rawValue is bool) {
bool value = (bool)rawValue;
//Do something
} else {
//It's not a bool
}
Unlike reference types, there's no fast way to try to cast to a value type without two casts. (Or a catch block, which would be worse)
bool value;
if(rawValue is bool)
value = (bool)rawValue;
else {
// something is not right...
With C# 9 you can also simplify to:
if(rawValue is true)
{
//do stuff
}
You haven't defined what you want to have happen if rawValue is not convertible to bool. Common choices are to return false, null, or throw an exception. There's also the possibility of the string representation of rawValue to be convertible to a bool, such as Yes/No, True/False, 1/0, etc.
I would use bool.TryParse to do the conversion. This will succeed if rawValue is a bool or its string value is "True" or "False".
bool result;
if (!bool.TryParse(rawValue as string, out result))
{
// you need to decide what to do in this case
}
You can cast it to a bool? with the as keyword and check the HasValue property.
Providing you don't actually need to keep a reference to the rawValue, here's a one-liner using the GetValueOrDefault() method of the Nullable<T> structure:
bool value = (map.GetValue(key) as bool?).GetValueOrDefault();
You can also specify a default value using the method overload GetValueOrDefault(T).
If the goal is to have true only if the raw object is boolean 'true' then one-liner (rawValue as bool?)?? false will do:
object rawValue=null
(rawValue as bool?)?? false
false
rawValue="some string"
(rawValue as bool?)?? false
false
rawValue=true
(rawValue as bool?)?? false
true
rawValue="true"
(rawValue as bool?)?? false
false
rawValue=false
(rawValue as bool?)?? false
false
rawValue=""
(rawValue as bool?)?? false
false
rawValue=1
(rawValue as bool?)?? false
false
rawValue=new Dictionary<string,string>()
(rawValue as bool?)?? false
false`
I used this check before doing something with object
if(myCrazyObject.GetType().Equals(typeof(bool)))
{
//do smt with it
}
bool value = (rawValue is null) ? false : (bool)rawValue.value;
if rawValue is null then value will be false, otherwise value will receive the correct boolean value.
You can also try Convert.ToBoolean(rowValue);

Categories

Resources