Thursday, September 7, 2017

Function <anonymous method> doesn't return a value on all code paths (Action Statement)

Hello,
Given the code statement below, the code throws an exception such as anonymous method does not return a value on all code paths.
If txtEmployeeHireDate.IsHandleCreated Then
 If txtEmployeeHireDate.InvokeRequired Then
  BeginInvoke(New Action(Function()
     txtEmployeeHireDate.Text = objEmployee.HireDate
     End Function))
 End If
End If
The code that's inside the BeginInvoke() statement does not necessarily returns a value since I only assigned an object's property value to the textbox control. In order to resolve this, either return a null value or a false value inside the Action delegate.
If txtEmployeeHireDate.IsHandleCreated Then
 If txtEmployeeHireDate.InvokeRequired Then
  BeginInvoke(New Action(Function()
     txtEmployeeHireDate.Text = objEmployee.HireDate
     Return Nothing 'added this statement to fix issue
     End Function))
 End If
End If
Another solution is to use Sub() which does not return a value instead of Function().
If txtEmployeeHireDate.IsHandleCreated Then
 If txtEmployeeHireDate.InvokeRequired Then
  BeginInvoke(New Action(Sub()
     txtEmployeeHireDate.Text = objEmployee.HireDate
     End Sub))
 End If
End If
C# Code
if (txtEmployeeHireDate.IsHandleCreated) {
 if (txtEmployeeHireDate.InvokeRequired) {
  BeginInvoke(new Action(() => { txtEmployeeHireDate.Text = objEmployee.HireDate; }));
 }
}

0 comments:

Post a Comment