Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HowToDetectIfADictionaryKeyExistsInCsharp
{
public class MyClass
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HowToDetectIfADictionaryKeyExistsInCsharp
{
public class MyClassWithEquality
public class MyClassWithEquality : IEquatable<MyClassWithEquality>
{
public int MyNumber { get; set; }

Expand All @@ -16,15 +9,11 @@ public MyClassWithEquality(int num)
MyNumber = num;
}

public bool Equals(MyClassWithEquality other)
{
if (this.MyNumber != other.MyNumber) return false;
return true;
}
public override bool Equals(object obj)
public bool Equals(MyClassWithEquality? other) => other is not null && MyNumber == other.MyNumber;

public override bool Equals(object? obj)
{
if (obj is not MyClassWithEquality) return false;
if (obj == null) return false;
return Equals(obj as MyClassWithEquality);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1 @@
using System;

namespace HowToDetectIfADictionaryKeyExistsInCsharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Console.WriteLine("Hello World!");
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using HowToDetectIfADictionaryKeyExistsInCsharp;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;

namespace Test
{
Expand Down Expand Up @@ -31,9 +29,9 @@ public void DictionaryContainsKeyUpdate()
Assert.IsTrue(SetOnceDictionary.ContainsKey("Banana"));
Assert.IsTrue(SetOnceDictionary.ContainsKey("Kiwi"));

Assert.IsTrue(SetOnceDictionary["Apple"] == 2);
Assert.IsTrue(SetOnceDictionary["Banana"] == 3);
Assert.IsTrue(SetOnceDictionary["Kiwi"] == 4);
Assert.AreEqual(2, SetOnceDictionary["Apple"]);
Assert.AreEqual(3, SetOnceDictionary["Banana"]);
Assert.AreEqual(4, SetOnceDictionary["Kiwi"]);
}
[TestMethod]
public void DictionaryCheckBeforeUse()
Expand All @@ -48,25 +46,18 @@ public void DictionaryCheckBeforeUse()

// Works, but risky!
int apples = MyDictionary["Apple"]; // 3
Assert.IsTrue(apples == 3);

// Throws an exception!
try
{
int kiwis = MyDictionary["Kiwi"];
}
catch (Exception e)
{
Assert.IsTrue(e is KeyNotFoundException);
}

Assert.AreEqual(3, apples);

// Throws an exception!
Assert.ThrowsExactly<KeyNotFoundException>(() => MyDictionary["Kiwi"]);

// Good practice
int oranges = 0;
if (MyDictionary.ContainsKey("Orange"))
{
oranges = MyDictionary["Orange"]; // 5
}
Assert.IsTrue(oranges == 5);
Assert.AreEqual(5, oranges);
}
[TestMethod]
public void DictionaryTryGetValue()
Expand All @@ -78,18 +69,20 @@ public void DictionaryTryGetValue()
{ "Orange", 5 },
{ "Pear", 2 }
};

int apples = 0;
bool ApplesSuccess = MyDictionary.TryGetValue("Apple", out apples); // ApplesSuccess == true, apples == 3
int kiwi = 0;
bool KiwisSuccess = MyDictionary.TryGetValue("Kiwi", out kiwi); // KiwisSuccess == false, kiwi == 0

// Same process, but more succinct:
ApplesSuccess = MyDictionary.TryGetValue("Apple", out int Apples); // ApplesSuccess == true, Apples == 3
KiwisSuccess = MyDictionary.TryGetValue("Kiwi", out int Kiwi); // KiwisSuccess == false, Kiwi == 0

Assert.IsTrue(Apples == 3);
Assert.IsTrue(Kiwi == 0);
Assert.AreEqual(3, Apples);
Assert.AreEqual(0, Kiwi);
Assert.IsTrue(ApplesSuccess);
Assert.IsFalse(KiwisSuccess);
}
[TestMethod]
public void DictionaryHasBanana()
Expand All @@ -107,6 +100,56 @@ public void DictionaryHasBanana()
Assert.IsTrue(DictionaryHasBanana);
}
[TestMethod]
public void DictionaryTryAdd()
{
var inventory = new Dictionary<string, int>()
{
{ "Apple", 2 },
{ "Banana", 3 }
};

var appleAdded = inventory.TryAdd("Apple", 4); // false, "Apple" is already there and keeps its 2
var kiwiAdded = inventory.TryAdd("Kiwi", 4); // true, "Kiwi" is inserted

Assert.IsFalse(appleAdded);
Assert.IsTrue(kiwiAdded);
Assert.AreEqual(2, inventory["Apple"]);
Assert.AreEqual(4, inventory["Kiwi"]);
}
[TestMethod]
public void DictionaryAddThrowsOnDuplicateKey()
{
var inventory = new Dictionary<string, int>() { { "Apple", 2 } };

Assert.ThrowsExactly<ArgumentException>(() => inventory.Add("Apple", 4));
}
[TestMethod]
public void DictionaryGetValueOrDefault()
{
var inventory = new Dictionary<string, int>() { { "Apple", 3 } };

Assert.AreEqual(3, inventory.GetValueOrDefault("Apple"));
Assert.AreEqual(0, inventory.GetValueOrDefault("Kiwi"));
Assert.AreEqual(99, inventory.GetValueOrDefault("Kiwi", 99));
}
[TestMethod]
public void DictionaryContainsValue()
{
var inventory = new Dictionary<string, int>() { { "Apple", 3 }, { "Banana", -2 } };

Assert.IsTrue(inventory.ContainsValue(-2));
Assert.IsFalse(inventory.ContainsValue(7));
}
[TestMethod]
public void DictionaryIsEmpty()
{
var empty = new Dictionary<string, int>();
var inventory = new Dictionary<string, int>() { { "Apple", 3 } };

Assert.AreEqual(0, empty.Count);
Assert.AreNotEqual(0, inventory.Count);
}
[TestMethod]
public void DictionaryEqualityCheck()
{
MyClass One = new MyClass(1);
Expand All @@ -128,5 +171,14 @@ public void DictionaryWithEquality()

Assert.IsTrue(MyDictionary.ContainsKey(AnotherOne));
}
[TestMethod]
public void DictionaryWithEqualityHandlesNull()
{
var one = new MyClassWithEquality(1);

Assert.IsFalse(one.Equals((MyClassWithEquality?)null));
Assert.IsFalse(one.Equals((object?)null));
Assert.IsTrue(EqualityComparer<MyClassWithEquality>.Default.Equals(one, new MyClassWithEquality(1)));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.3" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.3" />
<PackageReference Include="coverlet.collector" Version="3.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
<PackageReference Include="MSTest.TestAdapter" Version="4.3.3" />
<PackageReference Include="MSTest.TestFramework" Version="4.3.3" />
<PackageReference Include="coverlet.collector" Version="10.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading