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.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...