Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplified if else

Tags:

c#

if (File.Exists(file.csv))
{
   return file.csv;
}
else if (File.Exists(file.dbf))
{
   return file.dbf;
}

Can I simplify this expression using one line?

like image 552
user1765862 Avatar asked Jan 18 '26 07:01

user1765862


1 Answers

If you're willing to accept an InvalidOperationException if no matching file exists:

return new[]{file.csv, file.dbf}.First(File.Exists);

Edit:

If you don't want an exception (you removed that part from your question), use FirstOrDefault() instead and check for null, as Willem Duncan mentioned already in his comment.

like image 108
sloth Avatar answered Jan 19 '26 21:01

sloth