Skip to content

Commit 81dade6

Browse files
committed
Add Equals and HashCode to StringEnum
1 parent dc5e964 commit 81dade6

File tree

2 files changed

+77
-1
lines changed

2 files changed

+77
-1
lines changed

src/Twilio/Types/StringEnum.cs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace Twilio.Types
1+
using System;
2+
3+
namespace Twilio.Types
24
{
35
/// <summary>
46
/// Enum object for strings
@@ -38,6 +40,27 @@ public override string ToString()
3840
{
3941
return _value;
4042
}
43+
44+
public override int GetHashCode()
45+
{
46+
return _value.GetHashCode();
47+
}
48+
49+
public override bool Equals(object obj)
50+
{
51+
if (obj == null || !obj.GetType().Equals(GetType()))
52+
{
53+
return false;
54+
}
55+
56+
var o = (StringEnum) Convert.ChangeType(obj, GetType());
57+
if (o == null)
58+
{
59+
return false;
60+
}
61+
62+
return o._value.Equals(_value);
63+
}
4164
}
4265
}
4366

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
using System;
2+
using NUnit.Framework;
3+
using Twilio.Types;
4+
5+
namespace Twilio.Tests.Types
6+
{
7+
[TestFixture]
8+
public class StringEnumTest
9+
{
10+
public sealed class Enum1 : StringEnum
11+
{
12+
private Enum1(string value) : base(value) { }
13+
public Enum1() { }
14+
15+
public static readonly Enum1 V1 = new Enum1("v1");
16+
public static readonly Enum1 V2 = new Enum1("v2");
17+
}
18+
19+
public sealed class Enum2 : StringEnum
20+
{
21+
private Enum2(string value) : base(value) { }
22+
public Enum2() { }
23+
24+
public static readonly Enum2 V1 = new Enum2("v1");
25+
public static readonly Enum2 V2 = new Enum2("v2");
26+
}
27+
28+
[Test]
29+
public void TestEnumComparison()
30+
{
31+
Assert.AreNotEqual(Enum1.V1, Enum1.V2);
32+
Assert.AreNotEqual(Enum2.V2, Enum1.V2);
33+
Assert.AreEqual(Enum1.V1, Enum1.V1);
34+
}
35+
36+
public class Instance
37+
{
38+
public Enum1 E1 { get; set; }
39+
}
40+
41+
[Test]
42+
public void TestInstance()
43+
{
44+
var i = new Instance
45+
{
46+
E1 = Enum1.V1
47+
};
48+
49+
Assert.AreNotEqual(i.E1, Enum2.V1);
50+
Assert.AreEqual(i.E1, Enum1.V1);
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)