Answer the question
In order to leave comments, you need to log in
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
They don't, but if you want:
private static object OpenFile(string file)
{
...
}
var res = OpenFile(file);
if (res.GetType() == typeof(string))
{
var error = (string)res;
}
class ErrorStatus
{
public bool Status { get; private set; }
public string ErrorMessage { get; private set; }
public ErrorStatus(bool status, string errormessage)
{
Status = status;
ErrorMessage = errormessage;
}
}
private static ErrorStatus OpenFile(string file, out List<string> data)
{
...
}
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);
}
}
private void doTheBestBtn_Click(object sender, EventArgs e)
{
try {
var myList = ReadFromFile(txtInput.Text);
...
}
catch(ArgumentNullException ex) {
MessageBox.Show("Необходимо указать путь к файлу!");
}
catch(FileNotFoundException ex) {
MessageBox.Show("Указанный файл не найден!");
}
}
По правильному, нужно формировать Exception, если что-то идет не по плану и в обработчике предусматривать альтернативную логику
Подробнее
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question