Menu
Coddy logo textTech

Empty and Size

Part of the Logic & Flow section of Coddy's C# journey — lesson 60 of 66.

HashSets provide methods to check if they're empty and to determine their size.

Create an empty HashSet

HashSet<string> colors = new HashSet<string>();

Check if the HashSet is empty using Count

bool isEmpty = colors.Count == 0;
// isEmpty is true

Add some elements to the HashSet

colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");

Get the size of the HashSet

int size = colors.Count;
// size is 3

You can also check if a HashSet is empty using the Any() method

bool hasElements = colors.Any();
// hasElements is true since the set contains elements
challenge icon

Challenge

Easy

Create a method named CountAndCheck that takes a HashSet of strings as an argument. The method should:

  1. Check if the HashSet is empty.
  2. Print "Empty set" if it is empty.
  3. Otherwise, print "Set contains {count} elements" where {count} is the number of elements in the HashSet.

Cheat sheet

Check if a HashSet is empty using Count:

bool isEmpty = colors.Count == 0;

Get the size of a HashSet:

int size = colors.Count;

Check if a HashSet has elements using Any():

bool hasElements = colors.Any();

Try it yourself

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

class Program
{
    public static void CountAndCheck(HashSet<string> set)
    {
        // Write your code here
    }
    
    static void Main(string[] args)
    {
        // Read input for HashSet elements separated by commas
        // If the input is empty, create an empty HashSet
        string input = Console.ReadLine();
        
        HashSet<string> set = new HashSet<string>();
        if (!string.IsNullOrEmpty(input))
        {
            string[] elements = input.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        CountAndCheck(set);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow