Home > OS >  How do you return a string message from a method without the use of exceptions
How do you return a string message from a method without the use of exceptions

Time:05-23

class Device
{
public void AssignDevice(string playerName)
        {
            if (IsAssigned())
            {
                string message = "This device is already assinged to a player";
                MessageBox.Show(message);
            }
            else
            {
                this.playerName = playerName;
            }
        }
}

im trying to make a method that returns a string in a messageBox if it is true without the use of exceptions. is there any suggestions? this is made in winforms.

CodePudding user response:

As far as I'm concerned you should be able to get the response without working with Exceptions.

MessageBox.Show(message);    
if (result == System.Windows.Forms.DialogResult.Yes)
{
    // Closes the parent form.
    this.Close();
}

Or just check out the microsoft documentation

CodePudding user response:

Technically, you can just return some string, e.g. either error message or null when operation succeeds:

// return error message or null on success
public string AssignDevice(string playerName) {
   if (IsAssigned()) {
     string message = "This device is already assigned to a player";
     
     MessageBox.Show(message);

     return message; 
   }
   else
     this.playerName = playerName;
   
   return message;
}

Or using Try pattern:

// return true on success, false of error, message - error message  
public bool TryAssignDevice(string playerName, out string message) {
   string message = null;

   if (IsAssigned()) {
     message = "This device is already assigned to a player";

     return false; 
   }
   else
     this.playerName = playerName;
   
   return true;
}

usage

if (!TryAssignDevice(playerName, out var errorMessage)) {
  MessageBox.Show(errorMessage); 
}

The drawback of such approach (no exception but some return value(s)) is that the return can be easily ingored.

  •  Tags:  
  • c#
  • Related