1

I am currently parsing boolean into string using this line, but it ain't working all of times, is there any alternative ?

bool.Parse(listItem.Properties["Boolean Property"].ToString()) == false

2 Answers 2

2
bool? temp = listItem.Properties["Boolean Property"] as bool;
bool result = temp ?? true;

This code will read the property as a boolean, though return null if the property is null or not a bool (hence it is put into the nullable bool 'temp'). We then make it a normal bool use the ?? operator - if temp is null, result will be set to 'true'. Otherwise, result is set to whatever value temp has.

Using the '.Tostring()' risks a NullReferenceException if the property isn't set...

2
  • I was checking if property exists in code above using "ContainsField" but it was throwing exception for converting string into boolean but thanks anyway I give it a try, cheers Commented Oct 9, 2012 at 11:34
  • No problem, that's the pattern I use now, 'cos it avoids the .ToString (I did get caught but NullRef exceptions), and the same pattern works nicely with other types, such as ints. Commented Oct 9, 2012 at 11:35
0
string valueS = "true";

Convert.ToBoolean(valueS);

http://msdn.microsoft.com/en-us/library/wh2c31dd.aspx

hope it helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.