Menu
Coddy logo textTech

Adding an Element

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

The Add(element) method adds an element to the HashSet if it is not already present.

Create an empty HashSet:

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

Add "Apple" to the set:

fruits.Add("Apple");

After executing the above code, the set fruits contains:

{ "Apple" }

If you try to add the same element again, it won't be added twice:

fruits.Add("Apple"); // Returns false, element already exists

The HashSet remains unchanged:

{ "Apple" }
challenge icon

Challenge

Easy

Create a method named AddElement that takes two arguments:

  1. A HashSet of strings (set)
  2. A string (element) to add

The method should add the given element to the set and then print the updated set with each element separated by a comma and space. The elements should be enclosed in curly braces.

For example: { Apple, Banana, Cherry }

Cheat sheet

The Add(element) method adds an element to the HashSet if it is not already present.

Create an empty HashSet:

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

Add an element to the set:

fruits.Add("Apple");

If you try to add the same element again, it won't be added twice and returns false:

fruits.Add("Apple"); // Returns false, element already exists

Try it yourself

using System;
using System.Collections.Generic;

class Program
{
    public static void AddElement(HashSet<string> set, string element)
    {
        // Write your code here
    }
    
    public static void Main()
    {
        string[] initialElements = Console.ReadLine().Split(',');
        string elementToAdd = Console.ReadLine();
        
        HashSet<string> set = new HashSet<string>();
        foreach (string item in initialElements)
        {
            if (!string.IsNullOrWhiteSpace(item))
            {
                set.Add(item.Trim());
            }
        }
        
        AddElement(set, elementToAdd);
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow