'ASP.Net Nullable type throws Object reference not set to an instance of an object [closed]
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.
Solution 1:[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)
Solution 2:[2]
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)
{
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
