Convert.ToBoolean("1") throws System.Format Exception in C# - 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.

Related

How TryParse method works?

I have the following code.
using System;
class program
{
static void Main()
{
string StrNumber = "100TG";
int result = 0;
bool IsConversionSuccessful = int.TryParse(StrNumber, out result);
if (IsConversionSuccessful)
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("Invalid");
}
}
}
I know that TryParse method tries to convert StrNumber(100TG) into an integer.
And if it succeeds, it's going to save converted value into a result variable and return true for boolean.
And if it fails, a result value will remain as 0 and it will return false for boolean.
My question is that no matter what kind of boolean value IsConversionSuccessful variable gets, wouldn't "if(IsConversionSuccessful)" get activated? Am I misunderstanding TryParse Method?
If IsConversionSuccessful gets to be false, then the condition if(IsConverstionSuccessful) evaluates to if(false). Hence, the body of that if does not execute.
The TryParse method does not determine the execution of the next line in your program. It simply tells you whether the conversion from string to int was successful or not by returning a boolean value.
The lines following TryParse is up to you.
As you clearly have pointed out,
bool IsConversionSuccessful = int.TryParse(StrNumber, out result);
Will set IsConversionSuccessful to true/false based on how the method parsed the number.
If statements in themself evaluate something and always get a boolean answer, true or false. This is because if statements act like binary branch trees. They work like this:
When you evaluate if(A), which in your case is
if (IsConversionSuccessful)
The processor decides on a path to take and execution after that depends on the decision the processor made. Note that even excluding the else branch, an empty else branch simply points back to the "..." that comes after the if statement.

string to bool inline conversion

What I currently have:
bool okPress = !string.IsNullOrEmpty(Ctx.Request["okPress"]) &&
Convert.ToBoolean(Ctx.Request["okPress"]);
Correct me if I'm wrong here, but wouldn't this throw a FormatException if the string isn't "true/True" or "false/False"? Is there any way to handle the conversion in one row, without having to worry about exceptions? Or do I need to use Boolean.TryParse?
You can use Boolean.TryParse:
bool okPress;
bool success = Boolean.TryParse(Ctx.Request["okPress"]), out okPress);
For what it's worth, here a "one-liner", create following extension which might be useful especially in LINQ queries:
public static bool TryGetBool(this string item)
{
bool b;
Boolean.TryParse(item, out b);
return b;
}
and write:
bool okPress = Ctx.Request["okPress"].TryGetBool();
IF you didn't want to use TryParse You could do something like
bool okPress = !string.IsNullOrEmpty(Ctx.Request["okPress"]) &&
(Ctx.Request["okPress"].ToLower()=="true");
This way if the string is not true/false it will just assume false for you with no exceptions thrown.
This does of course assume that you are happy for a value of "fish" to be treated as false rather than as an exception.
Better though is to just not do it as a single line. You don't generally have a maximum number of lines of code so two or three simple lines of code are often better than one complicated line of code...
Why don't you compare the string against true?
bool okPress = !string.IsNullOrEmpty(Ctx.Request["okPress"]) &&
String.Compare(Ctx.Request["okPress"], "true", StringComparison.OrdinalIgnoreCase) == 0
You can use TryParse method of Boolean class as you said.
Tries to convert the specified string representation of a logical
value to its Boolean equivalent. A return value indicates whether the
conversion succeeded or failed.
bool result = Boolean.TryParse(Ctx.Request["okPress"]), out okPress);
It returns true if value was converted successfully; otherwise, false.
Your inline conversion.
public static bool TryParseAsBoolean(this string expression)
{
bool booleanValue;
bool.TryParse(expression, out booleanValue);
return booleanValue;
}
bool okPress = Ctx.Request["okPress"].TryParseAsBoolean();

Why use out keyword instead of assignment in c#?

I've been investigating the out keyword in C# after reading the section about it in C# in Depth. I cannot seem to find an example that shows why the keyword is required over just assigning the value of a return statement. For example:
public void Function1(int input, out int output)
{
output = input * 5;
}
public int Function2(int input)
{
return input * 5;
}
...
int i;
int j;
Function1(5, out i);
j = Function2(5);
Both i and j now have the same value. Is it just the convenience of being able to initialize without the = sign or is there some other value derived that I'm not seeing? I've seen some similar answers mentioning that it shifts responsibility for initialization to the callee here. But all that extra instead of just assigning a return value and not having a void method signature?
Usually out is used for a method that returns something else, but you still need to get a different value from the method.
A good example is Int32.TryParse(input, out myVar) it will return true if it was successful and false otherwise. You can get the converted int via the out parameter.
int myOutVar;
if (Int32.TryParse("2", out myOutVar))
{
//do something with the int
}else{
//Parsing failed, show a message
}
The out / ref keywords in C# should only be used when you need to return multiple values. Even then you should first consider using a container type (such as Tuple) to return multiple values before you revert to out / ref. Whenever you're returning a single value it should just be returned.
A lot of times, using out can help by giving you a slight performance gain.
Consider the TryGetValue method on IDictionary (say myDictionary is an IDictionary<string, string>) Rather than doing this:
string value = String.Empty;
if (myDictionary.ContainsKey("foo"))
{
value = myDictionary["foo"];
}
Both ContainsKey and the indexer need to look up the key in the dictionary, but you can avoid this double-lookup on the positive case by going:
string value;
if (!myDictionary.TryGetValue("foo", out value))
{
value = String.Empty;
}
IMO, that's a decent reason for using out parameters.
Unfortunately we cannot do something like below in C#:
a,b = func(x,y,z);
something that we do in Python or other languages. out kind of overcomes that.
F# has overcome this with tuples I believe.
PS: Returning multiple values from a function might not be good always. Tiny types are good most of the times - http://www.martinfowler.com/bliki/DataClump.html
For example, Int32.TryParse returns boolean if it parsed correctly and with the out parameter changes the value. If the parsed value is 0 and it returns true it means the value you sent to parse was 0. If it returns false then the parser failed.
Some of it is for clarity. Take the TryParse() methods, like
Int32.TryParse("3", out myInt);
This returns a bool that indicates whether the string was able to be parsed into an int.
If you just had
Int32.TryParse("3", myInt);
What happens when that's called? Is myInt assigned? Does TryParse return an int?
It's not readily apparent. But if I have an out parameter, then I know that the value is getting assigned, and that the return is something else.
Basically you do something like (my database read)
if (ReadSingle<UserRecord>(cmd, out user))
Cache.Insert(cacheId, user, null,
DateTime.MaxValue, TimeSpan.FromMinutes(3));
Or else you do something like:
user = ReadSingle<UserRecord>(cmd);
if(null != user)
// Cache.Insert ...
It simplifies the code a little to use a boolean result (that a record was read from the database) and get the actual record into the variable via the out keyword.

Equality comparison of the datatype of two strings value in C#

This is a weird requirement I have. I know even my question is quite confusing. Here is what I want to know.
I've two string variables. I need to do equality comparison of the datatype of the underlying value in the string variables. For ex.
string firstVariable = "123"; // It contains integer value. i.e. I can convert it to integer value
string secondVariable = "string" // It contains string value.
Now I need to compare whether datatype of the underlying values of these two strings are same. How can I do this?
Update: Thanks to all for the clarifications and answers. How about if I know the type of one variable?
For ex:
int firstVariable;
string secondVariable = "123".
Is this possible to check whether the type of the first variable equals to converted value of the secondVariable. When I declared firstVariable as int it doesn't mean it is always int type. What I mean here is, I know the type of one variable and other variable is string and I want compare equality of the datatypes of firstvariable and value datatype of the secondVariable.
Is Convert.ChangeType will anyway help in the above scenario?
I know this is silly question, but out of curiosity in the language feature exploring, I wanted to know this.
There's no such thing as the "underlying data type".
Who's to say that "123" isn't just a string containing the digits 1, 2 and 3? Once you've converted a value to a string, any information about the value you converted from - including its type - is lost.
Written from my head so there may (will) be errors:
class StringTypeEqualityComparer : IEqualityComparer<string, string>
{
public bool Equals(string x, string y)
{
int tempInt;
if (Int32.TryParse(x, out tempInt) && (Int32.TryParse(y, out tempInt))
return true;
bool tempBool;
if (Boolean.TryParse(x, out tempBool) && Boolean.TryParse(y, out tempBool))
return true;
float tempFloat;
if (Single.TryParse(x, out tempFloat) && Single.TryParse(y, out tempFloat))
return true;
// And whatever other types you want to compare...
return false;
// But what if two regular strings should also evaluate to equal?
}
}
Why do you need to compare them by the underlying data type?. Just compare them as string. Or if you have another variable as string, just convert it to a string by calling ToString() and make the comparison on the string level.
To do it you have to have a limited list of possible data types and be sure that type of your string content is not ambiguous. Then, for each type, you can try to convert string to it, so you will be able to find what type it actually was.

Difference between Forward and Reverse Comparison in C#

this is related to comparing values in C#.
basically by default, in C# till date i only used forward comparison as follows:
string value1 = "";
if (value1 == null)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
somewhere on Internet, i came across a link where it is said that while comparing values in C#, we should prefer Reverse Comparison as :
string value1 = "";
if (null == value1)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Now the problem is that is there any basic difference between the two ways of comparing values or not (i.e. both are same).
Looking for favorable replies.
Thanks
This is a hangover from languages where values are implicitly converted to a boolean type.
For the most part, anything that was non-null or non-0 would be treated as true, otherwise it was equivalent to false. This meant that any assignation of a constant would always be true.
This thing to remember here is that the assignment function returns the value assigned, much in the same way that 5 is the result of 2+3, myInt = 5 also returns 5.
Because of this, it was recommended that you check the variable against the constant. The null example is actually probably a bit contrived in this case, as it would, in most languages, return as false.
As an example:
if(i = 1)
{
printf("Always out\n");
}
else
{
printf("Never prints\n");
}
i is assigned the value of 1, which then returns the value of the assignment, 1, to the if statement. This is equivalent to true, and the if condition matches.
If you were to attempt to assign i to the constant 1, you wouldn't compile, and so it was recommended that you do things it that order (e.g. 1 == i).
This is not neccesary in C#, and further to your example, the recommended practice is to call if(String.IsNullOrEmpty(myStringValue)) { //.... }, as a string has... two ... default values from a semantic perspective.
Reverse comparison protects you from errors, when you use == (compare) instead of = (assign). But complier also warns you if you do this.

Categories

Resources