Is it possible to shorthand the code below?
Essentially metaItem.Text is a string property that contains either “true” or “false” – I’m dealing with objects I have no control over here so I know it should be a boolean instead.
First, I need to check if metaItem.Text contains a value (i.e. not an empty string). If so, convert it to a boolean. Then set the Visible property of a user control (relatedLinks) to that value.
if (metaItem.Text != string.Empty)
{
bool bShowRelatedLinks = false;
bool.TryParse(metaItem.Text, out bShowRelatedLinks);
if (bShowRelatedLinks)
{
relatedLinks.Visible = true;
}
else
{
relatedLinks.Visible = false;
}
}
The reasons for wanting to use shorthand is that I have a bunch of these conditions to show/hide various parts of the page.
Explanation: Firstly,
TryParse()can be givennull(it will set outoutparameter tofalseif parsing fails). Secondly, there’s no need for theiftest when settingrelatedLinks. You already have theboolvalue, so just assign that.If you’re certain that
metaItem.Textis"true","false", ornull, you can simplify further: