This should do:
string list = "";
lbxList.Invoke(new MethodInvoker(delegate
{
if (lbxList.SelectedItem != null)
list = lbxList.SelectedItem.ToString();
}));
//do something
Just place the if-statement inside the anonymous method.
Note that .ToString
is highly unlikely to ever return null
for anything, the documentation of object.ToString
states that overriding types should implement the method to return a meaningful value. Since we already know that .SelectedItem
is not null, checking for null is not really necessary. You can leave it in if you really want, but if you're afraid that .ToString
should return null, I would instead change the code to this:
string list = "";
lbxList.Invoke(new MethodInvoker(delegate
{
if (lbxList.SelectedItem != null)
list = lbxList.SelectedItem.ToString() ?? string.Empty;
}));
//do something