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 existsThe HashSet remains unchanged:
{ "Apple" }Challenge
EasyCreate a method named AddElement that takes two arguments:
- A HashSet of strings (
set) - 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 existsTry 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling8Data Analysis System
Data Collection SetupData Entry Logic11HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeRecap - HashSet3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety