I have the following code:
bool SilentUpdate { get; set;}
....
string temp = "";
SilentUpdate = Convert.ToBoolean(temp ?? "false");
I want to default SilentUpdate to false when temp string is empty. The above code still issue error "String was not recognized as a valid Boolean."
How can I do that?
This is slightly diffrent logic, but this will give you false for any value that does not correctly convert in to a Boolean which is likely what you are really looking for.
string temp = "";
bool result
if(!bool.TryParse(temp, out result))
{
result = false; //This line and the `if` is not actually necessary,
//result will be false if the parse fails.
}
SilentUpdate = result;
Using Convert.ToBoolean the string being parsed must either be a Boolean.TrueString, Boolean.FalseString or null. If it's any other value, then an exception will be thrown, so you must ensure to add a try...catch around the conversion code, example:
string temp = "nope";
SilentUpdate = Convert.ToBoolean(temp); // Exception: "String is not recognized as a valid Boolean"
Using Boolean.TryParse you can alleviate this, as well as get a default value as you're wanting:
string temp = "";
bool res = false;
SilentUpdate = (Boolean.TryParse(temp, out res) ? res : false);
Boolean.TryParse returns true or false if the parse succeeded and if it succeeded the ternary logic returns what was parsed, otherwise it's false.
Hope that can help.
You can use Boolean.TryParse() method as well. It returns bool based on whether the parsing has succeeded or not.
bool flag;
if (Boolean.TryParse(temp, out flag))
The code should be:
SilentUpdate = Convert.ToBoolean(string.IsNullOrEmpty(temp) ? "false" : temp)
You're misusing the ?? operator in your code. It only returns the second operand if the first one is null, not falsy. Empty string is not null and therefore temp ?? "false" returns the empty string, which is not a valid boolean value.
Related
I ma trying to convert json boolean value string to C# equivalent. This is my code:
string jsonResponseString = "{boolvalue:'true'}";
dynamic jsonResponse = JsonConvert.DeserializeObject(jsonResponseString);
if (jsonResponse.boolvalue == true){
Console.WriteLine("yes it is bool");
}
else{
Console.WriteLine("no it is still a string");
}
Unfortunately, boolvalue remains string "true" and not bool true. Since I will not know at runtime what kind of obkect string I am getting, I'd like to awoid explicit typecasting with DeserializeObject<type>. I feel like I am missing something obvious. What is the correct way of converting string bools to actual bool values?
The json value in your JSON string is literally the string true. For it to be parsed as a bool, you should declare it as a bool by removing the quotes:
string jsonResponseString = "{boolvalue: true}";
I've found out a strange behaviour of Convert.ToString and I would like to understand, why it does behave like this.
Have a look at following code pieces:
string obj = null;
var str = Convert.ToString(obj);
Console.WriteLine(str); // CORRECT: returns null;
all good so far, but:
DBNull obj = DBNull.Value;
var str = Convert.ToString(obj);
Console.WriteLine(str); // ???: returns string.Empty ("")
and
object obj = null;
var str = Convert.ToString(obj);
Console.WriteLine(str); // ???: returns string.Empty ("")
It looks to me like a bug, because when i do a conversion to a string and the input is NULL the result should be default of a string, which is also NULL.
Convert.ToString has a String overload that does nothing:
Returns the specified string instance; no actual conversion is performed.
and its Object overload is defined thus:
The string representation of value, or String.Empty if value is null.
It might be a bit surprising, but there’s no reason to use Convert.ToString on a String expression in the first place.
That's documented behaviour
Convert.ToString Method (Object)
The string representation of value, or String.Empty if value is null.
Convert.ToString Method (String)
value is returned unchanged.
I am trying to check if value exists in a string array. The below one works but when I tried the next code block, it failed.
bool exixts;
string toCheck= "jupiter";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck))
{
exists = true;
}
How can I check for trim and case sensitivity?
I tried this
bool exixts;
string toCheck= "jupiter ";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
{
exists = true;
}
The IEnumerable<string>.Contains(value, comparer) expects a compare class instance, not an enum value.
The library does have some ready made comparers available though:
//if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
if (printer.Contains(toCheck.Trim(), StringComparer.OrdinalIgnoreCase))
Or you can do like this,
bool exists = printer.Any(x=> x == toCheck.Trim());
Hope helps,
I'm trying to check if a string is a valid number or not. But this returns false. Why.
int IsNumber;
var parsed = int.TryParse("9876543210", NumberStyles.Number, null, out IsNumber);
if (parsed)
{
}
else
{
}
Also tried with CultureInfo.CurrentCulture.NumberFormat, instead of null.
When debugging, it never hits inside the if condition.
This should work
long IsNumber;
var parsed = long.TryParse("9876543210", NumberStyles.Number, null, out IsNumber);
if (parsed)
{
}
else
{
}
your code wasn't working because int.Max is 2147483647. If you want to check if all chars in string are digits, you can use Char.IsDigit:
var number = yourString.All(Char.IsDigit);
it will work for numbers bigger than max value of long ( 9223372036854775807)
If you are using it for validation (as you describe it) and you don't need to convert it to number type, use regular expression instead. This regular expression gives you information, whether the string contains numbers only
var stringToValidate = "9876543210"
Regex regex = new Regex(#"^\d$");
if (regex.IsMatch(compare))
{
//validation passed
}
Use BigInteger.TryParse Method. BigInteger represents an arbitrarily large signed integer.
Add this to using directives at top of page:
using System.Numerics;
Then:
BigInteger IsNumber;
var parsed = BigInteger.TryParse("9876543210", NumberStyles.Integer, null, out IsNumber);
if (parsed)
{
}
else
{
}
string mvi = Moneys.GetValue(8) as string;
if (mvi == null)
// I am getting exception Here if its null?
money.Currency= Convert.ToDecimal("");
else
// Currency is Decimal
money.Currency= Convert.ToDecimal(mvi);
// I am getting exception Here if its null?
money.Currency= Convert.ToDecimal("");
Can anybody tell me how to do this?
Empty string is not convertible to decimal. You could perform a check like this
if (string.IsNullOrEmpty(mvi))
{
money.Currency = 0M;
}
else
{
decimal temp = 0M;
if (decimal.TryParse(mvi, out temp))
{
money.Currency = temp;
}
else
{
// you have an invalid input, handle
}
}
Here's my version of Anthony Pegram's answer:
string mvi = Moneys.GetValue(8) as string;
money.Currency = 0M;
if (!String.IsNullOrEmpty(mvi))
if (!Decimal.TryParse(mvi, out money.Currency))
throw new FormatException("mvi");
On the whole, it looks quite a bit like the one Alex made, only it treats empty as zero and shows more error-handling.
You can use TryParse instead of Convert.ToDecimal():
decimal theValue;
string mvi = Moneys.GetValue(8) as string;
Decimal.TryParse( mvi, out theValue );
alternatively, you can use the null coallescing operator to handle nulls preemtively:
var theValue = Convert.ToDecimal( mvi ?? "0" );
In both cases, however, you have to decide what to do if the value coming in is not a valid decimal.
http://msdn.microsoft.com/en-us/library/hf9z3s65.aspx
I think you want Convert.ToDecimal("0.0"); otherwise you get a EDIT: ArgumentNullException