Today, when calling a method that uses params mutable parameters in a .NET Core project, a null reference exception was triggered. It was originally thought that the method did not check the parameters null value, so the check null code was added:
public static void BuildBlogPostLinks(params BlogPostDto[] blogPosts) { if (blogPosts == null) return; foreach (var blogPost in blogPosts) { //... } }
The result was unexpected. The null reference exception continued. After carefully looking at the exception stack, I found that the null reference exception was thrown during foreach. You need to check null for blogPost during foreach.
The following sample code can verify this
class Program { static void Main(string[] args) { BuildBlogPostLinks(null); BlogPost blogPost = null; BuildBlogPostLinks(blogPost); } public static void BuildBlogPostLinks(params BlogPost[] blogPosts) { if (blogPosts == null) { ("blogPosts in null"); return; } foreach (var blogPost in blogPosts) { if (blogPost == null) { ("blogPost in null"); } else { (": " + ); } } } } public class BlogPost { public string Title { get; set; } }
The output result at runtime is
$ dotnet run
blogPosts in null
blogPost in null
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.