How to initialize a dictionary to an empty dictionary in C#?


To initialize a dictionary to an empty dictionary, use the Clear() method. It clears the dictionary and forms it as empty.

dict.Clear();

After that, use the Dictionary count property to check whether the list is empty or not −

if (dict.Count == 0) {
   Console.WriteLine("Dictionary is empty!");
}

Let us see the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {

         var dict = new Dictionary < string, string > ();
         dict.Clear();
         if (dict.Count == 0) {
            Console.WriteLine("Dictionary is empty!");
         }
      }
   }
}

Output

Dictionary is empty!

Updated on: 22-Jun-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements