S
S
stalerum2016-05-27 11:48:06
C++ / C#
stalerum, 2016-05-27 11:48:06

How to return a return response of a different type from a function?

For convenience, I wrote the code for opening a file in a new function.
How can I now implement the response from the function so that:
1. upon successful opening, get a List
2. upon fail, get, for example, a bool parameter or a string variable with an error text

private void btn_StartRegMail_Click(object sender, EventArgs e)
{
    var names = new List<string>();
    //Открываем файл с именами
    names = OpenFile(tB_names.Text);
}
// Открытие файла
private static List<string> OpenFile(string file)
{
    if (File.Exists(file) == true)
    {
        var list = new List<string>();
        FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
        using (StreamReader sr = new StreamReader(fs, Encoding.Default))
        {
            string temp = string.Empty;
            list.Add(temp);
        }
        fs.Close();
        return list;
    }
    else
    {
        MessageBox.Show("Указанный файл не найден!");
        //return "error";
    }
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
P
Peter, 2016-05-27
@stalerum

They don't, but if you want:

private static object OpenFile(string file)
{
...
}

And then
var res = OpenFile(file);
if (res.GetType() == typeof(string))
{
   var error = (string)res;
}

How to do it:
1. Define your class, for example
class ErrorStatus
{
   public bool Status { get; private set; }
   public string ErrorMessage { get; private set; }

  public ErrorStatus(bool status, string errormessage)
  {
     Status = status;
     ErrorMessage = errormessage;
  }
}

2. And you are already returning
private static ErrorStatus OpenFile(string file, out List<string> data)
{
...
}

F
Fat Lorrie, 2016-05-27
@Free_ze

If you generate a certain List, then with a non-critical error (the file is empty), you should return an empty List. If the error is critical (file not found, file cannot be opened for reading, invalid argument, null argument), then an exception should be thrown.

private static List<SomeType> ReadFromFile(string path) {
    if (path == null) {
        throw new ArgumentNullException("path");
    }
    if (File.Exists(path)) {
        string file = File.ReadAllText(path);
        ...
    } else {
        throw new FileNotFoundException(path);
    }
}

Then in the calling code, you can do checks:
private void  doTheBestBtn_Click(object sender, EventArgs e)
{
    try {
        var myList = ReadFromFile(txtInput.Text);
        ...
    }
    catch(ArgumentNullException ex) {
        MessageBox.Show("Необходимо указать путь к файлу!");
    }
    catch(FileNotFoundException ex) {
        MessageBox.Show("Указанный файл не найден!");
    }
}

PS File.ReadAllText throws some exceptions by itself, but let's assume it's a self-made type.

D
Dmitry Eremin, 2016-05-27
@EreminD

По правильному, нужно формировать Exception, если что-то идет не по плану и в обработчике предусматривать альтернативную логику
Подробнее

A
Alexander Movchan, 2016-05-27
@Alexander1705

При ошибке выбрасывайте исключение.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question