0

I'm trying to return either a List or a null depending on the situation and I tried to do this using nullables, but I get NullReferenceException.

Here's the code:

ExcelProcess

public static class ExcelProcess<T>
    {
        public static Task<List<T>>? Upload(IFormFile file)
        {
            if(Check(file.FileName) == false)
            {
                return null;
            }
            return ProcessExcel(file);
        }

        private static bool Check(string fileName)
        {
            if (fileName.EndsWith(".xls") || fileName.EndsWith(".xlsx") || fileName.EndsWith(".csv"))
            {
                return true;
            }
            return false;
        }

        private static async Task<List<T>> ProcessExcel(IFormFile file)
        {
            List<T> records;
            using (var reader = new StringReader(await ReadCsv(file)))
            {
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    records = csv.GetRecords<T>().ToList();
                }
            }
            return records;
        }
        private static async Task<string> ReadCsv(IFormFile file)
        {
            var result = new StringBuilder();
            using (var reader = new StreamReader(file.OpenReadStream()))
            {
                while (reader.Peek() >= 0)
                    result.AppendLine(await reader.ReadLineAsync());
            }
            return result.ToString();
        }
    }

Import

public async Task<IActionResult> ImportJudete(IFormFile file)
        {
            List<JudetRequest>? judeteExcel 
= await ExcelProcess<JudetRequest>.Upload(file); //here I get the NullReferenceException and I get 500 Server Error
            ///....
        }

Why am I getting this exception? Shouldn't it stop because that type is nullable?

Thanks.

Octavian Niculescu
  • 1,177
  • 1
  • 3
  • 24
  • 1
    What exact line throws the exception? Which exact variable is null? Have you read through the general advice? https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – gunr2171 May 24 '22 at 14:13
  • @gunr2171 sorry, I intended the second piece of code differently so you can see where I get the exception – Octavian Niculescu May 24 '22 at 14:14
  • 1
    This `Task>?` is a nullable Task that results in a non-nullable List of T. I think you intended `Task?>`. – juunas May 24 '22 at 14:16
  • Still doesn't answer my questions. I see you get an exception from _calling_ `ExcelProcess.Upload(file)`, but most likely the exception is being thrown from within that method. – gunr2171 May 24 '22 at 14:17
  • @juunas I tried it too, modifying the upload function like this. public static Task?> Upload(IFormFile file) still the same :) – Octavian Niculescu May 24 '22 at 14:17
  • @gunr2171 that line throws the exception. I get null from Upload (when Check is false). – Octavian Niculescu May 24 '22 at 14:18
  • Why is the Upload method returning a Task at all? Nothing in the method is async, and you're not awaiting anything. You've posted a lot of code that doesn't seem relevant to your question (a lot of posted code won't run when `Check` returns false, and it doesn't matter what `Check`'s implementation is unless that method is throwing the exception). Please post a [mre]. – gunr2171 May 24 '22 at 14:21
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Fildor May 24 '22 at 14:21
  • @gunr2171 because it calls ProcessExcel which returns a task. – Octavian Niculescu May 24 '22 at 14:22
  • @Fildor no - I checked that question already. Thanks though – Octavian Niculescu May 24 '22 at 14:22
  • You're not awaiting any async methods. – gunr2171 May 24 '22 at 14:22
  • @gunr2171 if it doesn't return a task, it won't work, because ProcessExcel returns a Task. I'm a beginner in C# & ASP.NET, if this is a bad design, please show me what I should change and way, it would help a lot. – Octavian Niculescu May 24 '22 at 14:24

2 Answers2

1

Return null is not a good practice. Try to return an empty list instead.

Also make sure the file is not null. This line is bug prone. If file is null, it will throw an exception.

if(Check(file.FileName) == false)
0

Looks like your Upload method is returning a nullable Task rather than a nullable List. Since List is Nullable by default I guess this might work:

public async static Task<List<T>> Upload(IFormFile file)
{
    ...
}

And then used like this:

var uploadResult = await Upload(file);
if (uploadResult == null)
{
    ...
}
OldDev
  • 16
  • 1