Studies show that good grammar leads to more promotions and higher salaries. Write with Grammarly

C# Error CS0186 – Use of null is not valid in this context

C# Compiler Error

CS0186 – Use of null is not valid in this context

Reason for the Error

You will receive this error when you have used null keyword which should not be used in a specific context.

Lets take an example. The below code snippet results with the error code CS0186 because we have used null keyword directly instead of the collections in the foreach loop which is not allowed in C#.

using System;

namespace DeveloperPubNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (int index in null)
            {
                Console.WriteLine(index);
            }
        }
    }
  
}

Error CS0186 Use of null is not valid in this context ConsoleApp3 C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 10 Active

C# Error CS0186 - Use of null is not valid in this context

Solution

To fix the error, ensure that the null keyword is used in the right context. Remove null keyword from the usage and replace it with right type.