Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted
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...

share|improve this answer
    
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 –  Muhammad Raja Oct 9 '12 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. –  Andy Burns Oct 9 '12 at 11:35
add comment
string valueS = "true";

Convert.ToBoolean(valueS);

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

hope it helps :)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.