├── images
└── intellisense.gif
├── StringEnum.Tests
├── Enums
│ ├── Color.cs
│ ├── ColorWithImplicitParse.cs
│ └── ColorWithImplicitCreate.cs
├── StringEnum.Tests.csproj
├── DictionaryKeyTest.cs
├── StringEnumJsonConverter.cs
├── DuplicatedValuesTest.cs
├── JsonTests.cs
└── StringEnumTests.cs
├── StringEnum.Sample.NewtonsoftSerialization
├── TestEnum.cs
├── StringEnum.Sample.NewtonsoftSerialization.csproj
├── JsonUsageExample.cs
├── README.md
└── StringEnum.cs
├── LICENSE
├── StringEnum.sln
├── StringEnum
├── StringEnum.csproj
└── StringEnum.cs
├── README.md
└── .gitignore
/images/intellisense.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gerardog/StringEnum/HEAD/images/intellisense.gif
--------------------------------------------------------------------------------
/StringEnum.Tests/Enums/Color.cs:
--------------------------------------------------------------------------------
1 | namespace StringEnum.Tests
2 | {
3 | ///
4 | class Color : StringEnum
5 | {
6 | public static readonly Color Blue = Create("Blue");
7 | public static readonly Color Red = Create("Red");
8 | public static readonly Color Green = Create("Green");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/StringEnum.Sample.NewtonsoftSerialization/TestEnum.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace StringEnum.Sample.NewtonsoftSerialization
6 | {
7 | class Animal : StringEnum
8 | {
9 | public static readonly Animal Cat = Create("Cat");
10 | public static readonly Animal Dog = Create("Dog");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/StringEnum.Sample.NewtonsoftSerialization/StringEnum.Sample.NewtonsoftSerialization.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.1
5 |
6 | false
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/StringEnum.Tests/Enums/ColorWithImplicitParse.cs:
--------------------------------------------------------------------------------
1 | namespace StringEnum.Tests
2 | {
3 | ///
4 | class ColorWithImplicitParse : StringEnum
5 | {
6 | public static readonly ColorWithImplicitParse Blue = Create(nameof(Blue));
7 | public static readonly ColorWithImplicitParse Red = Create(nameof(Red));
8 | public static readonly ColorWithImplicitParse Green = Create(nameof(Green));
9 |
10 | public static implicit operator ColorWithImplicitParse(string stringValue) => Parse(stringValue, caseSensitive: false);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/StringEnum.Tests/StringEnum.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.1
5 |
6 | false
7 |
8 | StringEnum.Tests
9 |
10 | StringEnum.Tests
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/StringEnum.Tests/DictionaryKeyTest.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using System.Collections.Generic;
3 |
4 | namespace StringEnum.Tests
5 | {
6 | [TestClass]
7 | public class DictionaryKeyTest
8 | {
9 | [TestMethod]
10 | public void UsageAsDictionaryKeyTest()
11 | {
12 | var myDic = new Dictionary();
13 | myDic.Add(Color.Blue, 1);
14 | myDic.Add(Color.Green, 2);
15 | myDic.Add(Color.Red, 3);
16 |
17 | Assert.AreEqual(myDic[Color.Blue], 1);
18 | Assert.AreEqual(myDic[Color.Green], 2);
19 | Assert.AreEqual(myDic[Color.Red], 3);
20 |
21 | Assert.AreEqual(myDic[Color.Parse("Blue")], 1);
22 | Assert.AreEqual(myDic[Color.Parse("Green")], 2);
23 | Assert.AreEqual(myDic[Color.Parse("Red")], 3);
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/StringEnum.Tests/Enums/ColorWithImplicitCreate.cs:
--------------------------------------------------------------------------------
1 | namespace StringEnum.Tests
2 | {
3 | ///
4 | /// Color enum but with an implicit cast-from-string that invokes the Create() method, allowing any string to be casted as Color.
5 | ///
6 | ///
7 | class ColorWithImplicitCreate : StringEnum
8 | {
9 | public static readonly ColorWithImplicitCreate Blue = Create("Blue");
10 | public static readonly ColorWithImplicitCreate Red = Create("Red");
11 | public static readonly ColorWithImplicitCreate Green = Create("Green");
12 |
13 | // Added implicit conversion from string
14 | public static implicit operator ColorWithImplicitCreate(string stringValue)
15 | // Create new only if parsing fails, (i.e. it was not created with Create() before).
16 | => TryParse(stringValue, true) ?? Create(stringValue);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/StringEnum.Sample.NewtonsoftSerialization/JsonUsageExample.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using Newtonsoft.Json;
3 |
4 | namespace StringEnum.Sample.NewtonsoftSerialization
5 | {
6 | [TestClass]
7 | public class JsonUsageExample
8 | {
9 | const string expected = "{\"MyAnimal\":\"Cat\",\"MyString\":\"HelloWorld\"}";
10 |
11 | [TestMethod]
12 | public void Serialize()
13 | {
14 | var obj = new { MyAnimal = Animal.Cat, MyString = "HelloWorld" };
15 | var str = JsonConvert.SerializeObject(obj, new StringEnumJsonConverter());
16 | Assert.AreEqual(expected, str);
17 | }
18 |
19 | [TestMethod]
20 | public void Deserialize()
21 | {
22 | var obj = new { MyAnimal = (Animal)null, MyString = string.Empty };
23 | var result = JsonConvert.DeserializeAnonymousType(expected, obj);
24 |
25 | Assert.AreEqual("HelloWorld", result.MyString);
26 | Assert.AreEqual(Animal.Cat, result.MyAnimal);
27 | }
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | This is free and unencumbered software released into the public domain.
2 |
3 | Anyone is free to copy, modify, publish, use, compile, sell, or
4 | distribute this software, either in source code form or as a compiled
5 | binary, for any purpose, commercial or non-commercial, and by any
6 | means.
7 |
8 | In jurisdictions that recognize copyright laws, the author or authors
9 | of this software dedicate any and all copyright interest in the
10 | software to the public domain. We make this dedication for the benefit
11 | of the public at large and to the detriment of our heirs and
12 | successors. We intend this dedication to be an overt act of
13 | relinquishment in perpetuity of all present and future rights to this
14 | software under copyright law.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 | OTHER DEALINGS IN THE SOFTWARE.
23 |
24 | For more information, please refer to
25 |
--------------------------------------------------------------------------------
/StringEnum.Tests/StringEnumJsonConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Reflection;
4 |
5 | namespace StringEnum.Tests
6 | {
7 | public class StringEnumJsonConverter : JsonConverter
8 | {
9 | public override bool CanConvert(Type objectType)
10 | {
11 | return IsSubclassOfRawGeneric(typeof(StringEnum<>), objectType);
12 | }
13 |
14 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
15 | {
16 | writer.WriteValue(value.ToString());
17 | }
18 |
19 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
20 | {
21 | string s = (string)reader.Value;
22 | return typeof(StringEnum<>)
23 | .MakeGenericType(objectType)
24 | .GetMethod("Parse", BindingFlags.Public | BindingFlags.Static)
25 | .Invoke(null, new object[] { s, false });
26 | ;
27 | }
28 |
29 | static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
30 | {
31 | while (toCheck != null && toCheck != typeof(object))
32 | {
33 | var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
34 | if (generic == cur)
35 | {
36 | return true;
37 | }
38 | toCheck = toCheck.BaseType;
39 | }
40 | return false;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/StringEnum.Tests/DuplicatedValuesTest.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using System;
3 |
4 | namespace StringEnum.Tests
5 | {
6 | ///
7 | /// This class represents the common copy/paste typo when 2 items have the same value.
8 | ///
9 | class InvalidEnum : StringEnum
10 | {
11 | public static readonly InvalidEnum ItemOne = Create("ItemOne");
12 | public static readonly InvalidEnum ItemTwo = Create("ItemOne"); // <-- Intended duplicated value
13 | }
14 |
15 | ///
16 | /// What if it wasn't a typo and you need two enums with the same string. Create() the first one, Parse() the rest.
17 | ///
18 | class InvalidEnumWorkaround : StringEnum
19 | {
20 | public static readonly InvalidEnum ItemOne = Create("ItemOne");
21 | public static readonly InvalidEnum ItemTwo = Parse("ItemOne"); // <-- Allowed duplicated value via workaround.
22 | // In this case, order matters. Put the Create call before the Parse.
23 | }
24 |
25 | [TestClass]
26 | public class DuplicatedValuesTest
27 | {
28 | [TestMethod]
29 | [ExpectedException(typeof(TypeInitializationException))]
30 | public void InvalidEnum_ShouldFail()
31 | {
32 | var item1 = InvalidEnum.ItemOne; // When you try to call the enum, it throws.
33 | }
34 |
35 | [TestMethod]
36 | public void InvalidEnumWorkAround_Ok()
37 | {
38 | var item1 = InvalidEnumWorkaround.ItemOne;
39 | var item2 = InvalidEnumWorkaround.ItemTwo;
40 | var item3 = InvalidEnumWorkaround.Parse("ItemOne");
41 |
42 | Assert.IsTrue(item1 == item2);
43 | Assert.IsTrue(item1 == item3);
44 | Assert.IsTrue(item1.Equals(item2));
45 | Assert.IsTrue(item1.Equals(item3));
46 | Assert.IsTrue(object.ReferenceEquals(item1, item2));
47 | Assert.IsTrue(object.ReferenceEquals(item1, item3));
48 | }
49 |
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/StringEnum.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29215.179
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StringEnum", "StringEnum\StringEnum.csproj", "{74349787-6EB9-4E6C-BB3C-0A41BA077EDD}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StringEnum.Tests", "StringEnum.Tests\StringEnum.Tests.csproj", "{269049C7-5A1E-4552-B38A-778B678AC591}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StringEnum.Sample.NewtonsoftSerialization", "StringEnum.Sample.NewtonsoftSerialization\StringEnum.Sample.NewtonsoftSerialization.csproj", "{A059B763-E889-4606-A192-9BED72C6DA7E}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {74349787-6EB9-4E6C-BB3C-0A41BA077EDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {74349787-6EB9-4E6C-BB3C-0A41BA077EDD}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {74349787-6EB9-4E6C-BB3C-0A41BA077EDD}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {74349787-6EB9-4E6C-BB3C-0A41BA077EDD}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {269049C7-5A1E-4552-B38A-778B678AC591}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {269049C7-5A1E-4552-B38A-778B678AC591}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {269049C7-5A1E-4552-B38A-778B678AC591}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {269049C7-5A1E-4552-B38A-778B678AC591}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {A059B763-E889-4606-A192-9BED72C6DA7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {A059B763-E889-4606-A192-9BED72C6DA7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {A059B763-E889-4606-A192-9BED72C6DA7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {A059B763-E889-4606-A192-9BED72C6DA7E}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {DBFE31D0-3A04-49B8-985A-254251DD13E9}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/StringEnum/StringEnum.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard1.0
5 | StringEnum
6 | StringEnum
7 | true
8 | Gerardo Grignoli
9 | https://github.com/gerardog/StringEnum
10 | git
11 | string valued enum enumstring stringenum
12 | 0.1
13 | true
14 | StringEnumKeyFile.pfx
15 | false
16 | StringEnum is a base class for creating string-valued enums in .NET.
17 |
18 | Features
19 | - Your StringEnum interface looks similar to a regular enum
20 | - Provides static Parse() and TryParse() methods and implicit cast to string.
21 | - Intellisense will suggest the enum name if the class is annotated with the xml comment `<completitionlist>`. (Works in both C# and VB)
22 |
23 | Usage:
24 |
25 | ///<completionlist cref="HexColor"/>
26 | class HexColor : StringEnum<HexColor>
27 | {
28 | public static readonly HexColor Blue = Create("#FF0000");
29 | public static readonly HexColor Green = Create("#00FF00");
30 | public static readonly HexColor Red = Create("#000FF");
31 | }
32 |
33 | // Static Parse Method
34 | HexColor.Parse("#FF0000") // => HexColor.Red
35 | HexColor.Parse("#ff0000", caseSensitive: false) // => HexColor.Red
36 | HexColor.Parse("invalid") // => throws InvalidOperationException
37 |
38 | // Static TryParse method.
39 | HexColor.TryParse("#FF0000") // => HexColor.Red
40 | HexColor.TryParse("#ff0000", caseSensitive: false) // => HexColor.Red
41 | HexColor.TryParse("invalid") // => null
42 |
43 | // Conversion from your `StringEnum` to `string`
44 | string myString1 = HexColor.Red.ToString(); // => "#FF0000"
45 | string myString2 = HexColor.Red; // => "#FF0000" (implicit cast)
46 |
47 | 2019 Gerardo Grignoli
48 | MIT
49 | https://github.com/gerardog/StringEnum
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/StringEnum.Tests/JsonTests.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using Newtonsoft.Json;
3 | using StringEnum;
4 | using System;
5 | using System.Reflection;
6 |
7 | namespace StringEnum.Tests
8 | {
9 | [Newtonsoft.Json.JsonConverter(typeof(StringEnumJsonConverter))]
10 | class JsonSerializableColor : StringEnum
11 | {
12 | public static readonly JsonSerializableColor Blue = Create("Blue");
13 | public static readonly JsonSerializableColor Red = Create("Red");
14 | public static readonly JsonSerializableColor Green = Create("Green");
15 | }
16 |
17 | [Microsoft.VisualStudio.TestTools.UnitTesting.TestClass]
18 | public class JsonTests
19 | {
20 | const string expected = "{\"Color\":\"Red\",\"MyString\":\"HelloWorld\"}";
21 |
22 | [TestMethod]
23 | public void SerializeJsonMarked()
24 | {
25 | var obj = new { Color = JsonSerializableColor.Red, MyString = "HelloWorld" };
26 | var str = JsonConvert.SerializeObject(obj);
27 | Assert.AreEqual(expected, str);
28 | }
29 |
30 | [TestMethod]
31 | public void DeserializeJsonMarked()
32 | {
33 | var obj = new { Color = (JsonSerializableColor)null, MyString = string.Empty };
34 |
35 | var str = JsonConvert.DeserializeAnonymousType(expected, obj);
36 |
37 | Assert.AreEqual("HelloWorld", str.MyString);
38 | Assert.AreEqual(JsonSerializableColor.Red, str.Color);
39 | }
40 |
41 | [TestMethod]
42 | // Serialize a class not marked as serializable
43 | public void SerializeNotMarked()
44 | {
45 | var obj = new { Color = Color.Red, MyString = "HelloWorld" };
46 | var str = JsonConvert.SerializeObject(obj, new StringEnumJsonConverter());
47 | Assert.AreEqual(expected, str);
48 | }
49 |
50 | [TestMethod]
51 | // De-Serialize a class not marked as serializable
52 | public void DeserializeNotMarked()
53 | {
54 | var obj = new { Color = (Color)null, MyString = string.Empty };
55 |
56 | var settings = new JsonSerializerSettings();
57 | settings.Converters.Add(new StringEnumJsonConverter());
58 | var result = JsonConvert.DeserializeAnonymousType(expected, obj, settings);
59 |
60 | Assert.AreEqual("HelloWorld", result.MyString);
61 | Assert.AreEqual(Color.Red, result.Color);
62 | }
63 | }
64 | }
--------------------------------------------------------------------------------
/StringEnum.Sample.NewtonsoftSerialization/README.md:
--------------------------------------------------------------------------------
1 | # StringEnum Newtonsoft.Json serialization
2 |
3 | Json serialization was not built into the NuGet package to avoid a possibly unneeded dependency on `Newtonsoft.Json`.
4 |
5 | To add `Json.Net` serialization support you need the `StringEnumJsonConverter` class.
6 |
7 | This extended version file has everything in one: [StringEnum.cs](StringEnum.cs).
8 |
9 | Or:
10 |
11 | - Add [StringEnumJsonConverter](StringEnum.cs#59) class to your code.
12 |
13 | ``` csharp
14 | using Newtonsoft.Json;
15 | using System;
16 | using System.Reflection;
17 |
18 | public class StringEnumJsonConverter : JsonConverter
19 | {
20 | public override bool CanConvert(Type objectType)
21 | {
22 | return IsSubclassOfRawGeneric(typeof(StringEnum<>), objectType);
23 | }
24 |
25 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
26 | {
27 | writer.WriteValue(value.ToString());
28 | }
29 |
30 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
31 | {
32 | string s = (string)reader.Value;
33 | return typeof(StringEnum<>)
34 | .MakeGenericType(objectType)
35 | .GetMethod("Parse", BindingFlags.Public | BindingFlags.Static)
36 | .Invoke(null, new object[] { s, false });
37 | }
38 |
39 | static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
40 | {
41 | while (toCheck != null && toCheck != typeof(object))
42 | {
43 | var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
44 | if (generic == cur)
45 | {
46 | return true;
47 | }
48 | toCheck = toCheck.BaseType;
49 | }
50 | return false;
51 | }
52 | }
53 | ```
54 |
55 | - Adding the following attribute to the `StringEnum` base class to support all instances, or add it to your specific StringEnums:
56 |
57 | ``` csharp
58 | [Newtonsoft.Json.JsonConverter(typeof(StringEnumJsonConverter))]
59 | ```
60 |
61 | - You can also avoid the attributes and inject the `StringEnumJsonConverter` when you setup your (de)serialization:
62 |
63 | ``` csharp
64 | //serialization
65 | var obj = new { Color = Color.Red, MyString = "HelloWorld" };
66 | var jsonString = JsonConvert.SerializeObject(obj, new StringEnumConverter());
67 |
68 | //deserealization
69 | var settings = new JsonSerializerSettings();
70 | settings.Converters.Add(new StringEnumConverter());
71 |
72 | var result = JsonConvert.DeserializeAnonymousType(jsonString, obj, settings);
73 | Assert.AreEqual(Color.Red, result.Color);
74 | ```
75 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # StringEnum
2 |
3 | StringEnum is a base class for creating string-valued enums in .NET. It is just one C# file that you can copy & paste into your projects, or install via NuGet package named [StringEnum](https://www.nuget.org/packages/StringEnum/).
4 |
5 | ## Usage:
6 |
7 | ``` csharp
8 | ///
9 | class HexColor : StringEnum
10 | {
11 | public static readonly HexColor Blue = Create("#FF0000");
12 | public static readonly HexColor Green = Create("#00FF00");
13 | public static readonly HexColor Red = Create("#000FF");
14 | }
15 | ```
16 |
17 | ## Features
18 |
19 | - Your StringEnum looks somewhat similar to a regular enum:
20 |
21 | ``` csharp
22 | // Static Parse Method
23 | HexColor.Parse("#FF0000") // => HexColor.Red
24 | HexColor.Parse("#ff0000", caseSensitive: false) // => HexColor.Red
25 | HexColor.Parse("invalid") // => throws InvalidOperationException
26 |
27 | // Static TryParse method.
28 | HexColor.TryParse("#FF0000") // => HexColor.Red
29 | HexColor.TryParse("#ff0000", caseSensitive: false) // => HexColor.Red
30 | HexColor.TryParse("invalid") // => null
31 |
32 | // Parse and TryParse returns the preexistent instances
33 | object.ReferenceEquals(HexColor.Parse("#FF0000"), HexColor.Red) // => true
34 |
35 | // Conversion from your `StringEnum` to `string`
36 | string myString1 = HexColor.Red.ToString(); // => "#FF0000"
37 | string myString2 = HexColor.Red; // => "#FF0000" (implicit cast)
38 | ```
39 |
40 | - Intellisense will suggest the enum name if the class is annotated with the xml comment ``. (Works in both C# and VB): i.e.
41 |
42 | 
43 |
44 | ### Installation
45 |
46 | Either:
47 |
48 | - Install [**StringEnum**](https://www.nuget.org/packages/StringEnum/) NuGet package, which is based on `.Net Standard 1.0` so it runs on `.Net Core` >= 1.0, `.Net Framework` >= 4.5, `Mono` >= 4.6, etc.
49 | - Or copy [StringEnum.cs](StringEnum/StringEnum.cs) base class to your project.
50 | - For `Newtonsoft.Json` serialization support, copy this extended version instead. [StringEnum.cs](StringEnum.Sample.NewtonsoftSerialization/StringEnum.cs), or follow the steps explained [here](StringEnum.Sample.NewtonsoftSerialization/README.md)
51 |
52 |
53 | ### Extensibility / Tips
54 |
55 | - You may add implicit casting **from string to your StringEnum**, by binding the implicit cast operator to the Parse method in the target class.
56 |
57 | ``` csharp
58 | class Color : StringEnum
59 | {
60 | public static readonly Color Blue = Create("Blue");
61 | public static readonly Color Green = Create("Green");
62 | ...add members..
63 |
64 | // Add the following line
65 | public static implicit operator Color(string stringValue)
66 | => Parse(stringValue, caseSensitive: false);
67 | }
68 |
69 | // usage:
70 | Color x = "Blue"; // implicit cast will then run: Color.Parse("Blue", caseSensitive: false)
71 | // or given a method:
72 | void PaintWall(Color wallColor)
73 | // you can call
74 | PaintWall("Blue");
75 | ```
76 |
77 | - To allow any string to be a casted as your StringEnum value, you may expose the Create() method as public:
78 |
79 | ``` csharp
80 | public new static MyEnum Create(string value) => StringEnum.Create(value);
81 | ```
82 |
83 | Or implement a special implicit cast:
84 |
85 | ``` csharp
86 | public static implicit operator MyEnum(string stringValue) => TryParse(stringValue, true) ?? Create(stringValue);
87 | ```
88 |
89 | However, I wouldn't recommend to use the Create() method with user-entered strings, as they will be stored in memory in the internal `valueDict` dictionary used for Parse and TryParse.
90 |
91 | - If your StringEnum member names are equal to the string value, you can use replace the string with `nameof(member name)`, so the string is inferred from the member itself. That way if you refactor the member name (i.e. Color.Blue -> Color.BLUE), the string will be changed too ("Blue" -> "BLUE").
92 |
93 | ``` csharp
94 | public static readonly Color Blue = Create(nameof(Blue)); // <-- use nameof(Blue) instead of "Blue" string literal
95 | ```
96 |
--------------------------------------------------------------------------------
/StringEnum/StringEnum.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 |
5 | namespace StringEnum
6 | {
7 | // For Newtonsoft.Json support check /StringEnum.Sample.NewtonsoftSerialization/StringEnum.cs .
8 | ///
9 | /// Base class for creating string-valued enums in .NET.
10 | /// Provides static Parse() and TryParse() methods and implicit cast to string.
11 | ///
12 | ///
13 | ///
14 | /// class Color : StringEnum <Color>
15 | /// {
16 | /// public static readonly Color Blue = Create("Blue");
17 | /// public static readonly Color Red = Create("Red");
18 | /// public static readonly Color Green = Create("Green");
19 | /// }
20 | ///
21 | ///
22 | /// The string-valued enum type. (i.e. class Color : StringEnum<Color>)
23 | public abstract class StringEnum : IEquatable where T : StringEnum, new()
24 | {
25 | protected string Value;
26 | private static Dictionary valueDict = new Dictionary();
27 | protected static T Create(string value)
28 | {
29 | if (value == null)
30 | return null; // the null-valued instance is null.
31 |
32 | var result = new T() { Value = value };
33 | valueDict.Add(value, result);
34 | return result;
35 | }
36 |
37 | public static implicit operator string(StringEnum enumValue) => enumValue.Value;
38 | public override string ToString() => Value;
39 |
40 | public static bool operator !=(StringEnum o1, StringEnum o2) => o1?.Value != o2?.Value;
41 | public static bool operator ==(StringEnum o1, StringEnum o2) => o1?.Value == o2?.Value;
42 |
43 | public override bool Equals(object other) => this.Value.Equals((other as T)?.Value ?? (other as string));
44 | bool IEquatable.Equals(T other) => this.Value.Equals(other.Value);
45 | public override int GetHashCode() => Value.GetHashCode();
46 |
47 | ///
48 | /// Parse the specified and returns a valid or else throws InvalidOperationException.
49 | ///
50 | /// The string value representad by an instance of . Matches by string value, not by the member name.
51 | /// If true, the strings must match case and takes O(log n). False allows different case but is little bit slower (O(n))
52 | public static T Parse(string value, bool caseSensitive = true)
53 | {
54 | var result = TryParse(value, caseSensitive);
55 | if (result == null)
56 | throw new InvalidOperationException((value == null ? "null" : $"'{value}'") + $" is not a valid {typeof(T).Name}");
57 |
58 | return result;
59 | }
60 |
61 | ///
62 | /// Parse the specified and returns a valid or else returns null.
63 | ///
64 | /// The string value representad by an instance of . Matches by string value, not by the member name.
65 | /// If true, the strings must match case. False allows different case but is slower: O(n)
66 | public static T TryParse(string value, bool caseSensitive = true)
67 | {
68 | if (value == null) return null;
69 | if (valueDict.Count == 0) System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); // force static fields initialization
70 | if (caseSensitive)
71 | {
72 | if (valueDict.TryGetValue(value, out T item))
73 | return item;
74 | else
75 | return null;
76 | }
77 | else
78 | {
79 | // slower O(n) case insensitive search
80 | return valueDict.FirstOrDefault(f => f.Key.Equals(value, StringComparison.OrdinalIgnoreCase)).Value;
81 | // Why Ordinal? => https://esmithy.net/2007/10/15/why-stringcomparisonordinal-is-usually-the-right-choice/
82 | }
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/StringEnum.Sample.NewtonsoftSerialization/StringEnum.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Reflection;
6 |
7 | namespace StringEnum
8 | {
9 | /// Version with Newtonsoft.Json support.
10 | ///
11 | /// Base class for creating string-valued enums in .NET.
12 | /// Provides static Parse() and TryParse() methods and implicit cast to string.
13 | ///
14 | ///
15 | ///
16 | /// class Color : StringEnum <Color>
17 | /// {
18 | /// public static readonly Color Blue = Create("Blue");
19 | /// public static readonly Color Red = Create("Red");
20 | /// public static readonly Color Green = Create("Green");
21 | /// }
22 | ///
23 | ///
24 | /// The string-valued enum type. (i.e. class Color : StringEnum<Color>)
25 | [JsonConverter(typeof(StringEnumJsonConverter))]
26 | public abstract class StringEnum : IEquatable where T : StringEnum, new()
27 | {
28 | protected string Value;
29 | private static Dictionary valueDict = new Dictionary();
30 | protected static T Create(string value)
31 | {
32 | if (value == null)
33 | return null; // the null-valued instance is null.
34 |
35 | var result = new T() { Value = value };
36 | valueDict.Add(value, result);
37 | return result;
38 | }
39 |
40 | public static implicit operator string(StringEnum enumValue) => enumValue.Value;
41 | public override string ToString() => Value;
42 |
43 | public static bool operator !=(StringEnum o1, StringEnum o2) => o1?.Value != o2?.Value;
44 | public static bool operator ==(StringEnum o1, StringEnum o2) => o1?.Value == o2?.Value;
45 |
46 | public override bool Equals(object other) => this.Value.Equals((other as T)?.Value ?? (other as string));
47 | bool IEquatable.Equals(T other) => this.Value.Equals(other.Value);
48 | public override int GetHashCode() => Value.GetHashCode();
49 |
50 | ///
51 | /// Parse the specified and returns a valid or else throws InvalidOperationException.
52 | ///
53 | /// The string value representad by an instance of . Matches by string value, not by the member name.
54 | /// If true, the strings must match case and takes O(log n). False allows different case but is little bit slower (O(n))
55 | public static T Parse(string value, bool caseSensitive = true)
56 | {
57 | var result = TryParse(value, caseSensitive);
58 | if (result == null)
59 | throw new InvalidOperationException((value == null ? "null" : $"'{value}'") + $" is not a valid {typeof(T).Name}");
60 |
61 | return result;
62 | }
63 |
64 | ///
65 | /// Parse the specified and returns a valid or else returns null.
66 | ///
67 | /// The string value representad by an instance of . Matches by string value, not by the member name.
68 | /// If true, the strings must match case. False allows different case but is slower: O(n)
69 | public static T TryParse(string value, bool caseSensitive = true)
70 | {
71 | if (value == null) return null;
72 | if (valueDict.Count == 0) System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); // force static fields initialization
73 | if (caseSensitive)
74 | {
75 | if (valueDict.TryGetValue(value, out T item))
76 | return item;
77 | else
78 | return null;
79 | }
80 | else
81 | {
82 | // slower O(n) case insensitive search
83 | return valueDict.FirstOrDefault(f => f.Key.Equals(value, StringComparison.OrdinalIgnoreCase)).Value;
84 | // Why Ordinal? => https://esmithy.net/2007/10/15/why-stringcomparisonordinal-is-usually-the-right-choice/
85 | }
86 | }
87 | }
88 | public class StringEnumJsonConverter : JsonConverter
89 | {
90 | public override bool CanConvert(Type objectType)
91 | {
92 | return IsSubclassOfRawGeneric(typeof(StringEnum<>), objectType);
93 | }
94 |
95 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
96 | {
97 | writer.WriteValue(value.ToString());
98 | }
99 |
100 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
101 | {
102 | string s = (string)reader.Value;
103 | return typeof(StringEnum<>)
104 | .MakeGenericType(objectType)
105 | .GetMethod("Parse", BindingFlags.Public | BindingFlags.Static)
106 | .Invoke(null, new object[] { s, false });
107 | ;
108 | }
109 |
110 | static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
111 | {
112 | while (toCheck != null && toCheck != typeof(object))
113 | {
114 | var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
115 | if (generic == cur)
116 | {
117 | return true;
118 | }
119 | toCheck = toCheck.BaseType;
120 | }
121 | return false;
122 | }
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 |
--------------------------------------------------------------------------------
/StringEnum.Tests/StringEnumTests.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using System;
3 | using System.Linq;
4 |
5 | namespace StringEnum.Tests
6 | {
7 | [TestClass]
8 | public class StringEnumTests
9 | {
10 | [TestMethod]
11 | public void StringEnumComparisonTests()
12 | {
13 | Color red1 = Color.Red;
14 | Color red2 = Color.Parse("Red");
15 | Color blue1 = Color.Blue;
16 | Color blue2 = Color.Parse("Blue");
17 | Color nullColor1 = (null as Color);
18 | Color nullColor2 = Color.TryParse(null as string);
19 |
20 | Assert.IsTrue(red1 == red2);
21 | Assert.IsFalse(red1 != red2);
22 | Assert.IsTrue(red1.Equals(red2));
23 |
24 | Assert.IsFalse(red1 == blue1);
25 | Assert.IsFalse(red1 == blue2);
26 | Assert.IsFalse(red2 == blue1);
27 | Assert.IsFalse(red2 == blue2);
28 |
29 | Assert.IsFalse(red1.Equals(blue1));
30 |
31 | Assert.IsFalse(red1 == null);
32 | Assert.IsFalse(null == red1);
33 |
34 | Assert.IsFalse(red1 == nullColor1);
35 | Assert.IsFalse(nullColor1 == red1);
36 |
37 | Assert.IsTrue(nullColor1 == nullColor2);
38 | Assert.IsFalse(nullColor1 != nullColor2);
39 |
40 | Assert.IsTrue(nullColor1 == null);
41 | Assert.IsTrue(null == nullColor1);
42 | Assert.IsTrue(nullColor2 == null);
43 | Assert.IsTrue(null == nullColor2);
44 |
45 | Assert.IsFalse(nullColor1 != null);
46 | Assert.IsFalse(null != nullColor1);
47 | Assert.IsFalse(nullColor2 != null);
48 | Assert.IsFalse(null != nullColor2);
49 |
50 | Assert.IsFalse(red1.Equals(nullColor2));
51 |
52 | Assert.AreEqual(Color.Red.GetHashCode(), "Red".GetHashCode());
53 | Assert.AreEqual(Color.Red.GetHashCode(), Color.Red.GetHashCode());
54 | }
55 |
56 | [TestMethod]
57 | public void StringComparisonTests()
58 | {
59 | // Case sensitive same value.
60 | Assert.IsTrue(Color.Red == "Red");
61 | Assert.IsTrue("Red" == Color.Red);
62 | Assert.IsTrue(Color.Red.Equals("Red"));
63 | Assert.IsTrue(("Red").Equals(Color.Red));
64 | Assert.IsFalse(Color.Red != "Red");
65 | Assert.IsFalse("Red" != Color.Red);
66 |
67 | // Case sensitive different case.
68 | Assert.IsFalse(Color.Red == "red");
69 | Assert.IsFalse("red" == Color.Red);
70 | Assert.IsFalse(Color.Red.Equals("red"));
71 | Assert.IsFalse(("red").Equals(Color.Red));
72 | Assert.IsTrue(Color.Red != "red");
73 | Assert.IsTrue("red" != Color.Red);
74 |
75 | // Case Insensitive same case/value.
76 | Assert.IsTrue(Color.Red == "Red");
77 | Assert.IsTrue("Red" == Color.Red);
78 | Assert.IsTrue(Color.Red.Equals("Red"));
79 | Assert.IsTrue("Red".Equals(Color.Red));
80 | Assert.IsFalse(Color.Red != "Red");
81 | Assert.IsFalse("Red" != Color.Red);
82 |
83 | // Case Insensitive different case.
84 | Assert.IsFalse(Color.Red == "red");
85 | Assert.IsFalse("red" == Color.Red);
86 | Assert.IsFalse(Color.Red.Equals("red"));
87 | Assert.IsFalse("red".Equals(Color.Red));
88 | Assert.IsTrue(Color.Red != "red");
89 | Assert.IsTrue("red" != Color.Red);
90 |
91 | // Case sensitive different values
92 | Assert.IsFalse(Color.Red == "Blue");
93 | Assert.IsFalse("Blue" == Color.Red);
94 | Assert.IsFalse(Color.Red.Equals("Blue"));
95 | Assert.IsFalse("Blue".Equals(Color.Red));
96 | Assert.IsTrue(Color.Red != "Blue");
97 | Assert.IsTrue("Blue" != Color.Red);
98 |
99 | // null value comparisons
100 | Assert.IsFalse(null == Color.Red);
101 | Assert.IsFalse(Color.Red == null);
102 | Assert.IsTrue(null != Color.Red);
103 | Assert.IsTrue(Color.Red != null);
104 | Assert.IsFalse(Color.Red.Equals(null));
105 | }
106 |
107 | [TestMethod]
108 | public void UsageTests()
109 | {
110 | var r1 = PaintWithColor(Color.Red);
111 | var r2 = PaintWithColor(Color.Parse("Red"));
112 |
113 | Assert.AreEqual("The wall is now Red", r1);
114 | Assert.AreEqual("The wall is now Red", r2);
115 |
116 | Assert.AreEqual("The wall is now Red,Blue,Green,Red,Blue,Green",
117 | PaintStripe(Color.Red, Color.Blue, Color.Green, Color.Parse("Red"), Color.Parse("Blue"), Color.Parse("Green"))
118 | );
119 | }
120 |
121 | private string PaintWithColor(Color wallColor)
122 | {
123 | return "The wall is now " + wallColor;
124 | }
125 |
126 | private string PaintStripe(params Color[] colors)
127 | {
128 | return "The wall is now " + string.Join(",", colors.Select(c => c.ToString()).ToArray());
129 | }
130 |
131 | [TestMethod]
132 | public void ParseTest_OK()
133 | {
134 | Color a = Color.Parse("Red", true);
135 | Assert.AreEqual(a, Color.Red);
136 |
137 | ColorWithImplicitParse b = "Red";
138 | Assert.AreEqual(b, ColorWithImplicitParse.Red);
139 | }
140 |
141 | [TestMethod]
142 | public void ParseTest_CaseInsensitiveOK()
143 | {
144 | Color a = Color.Parse("red", false);
145 | Assert.AreEqual(a, Color.Red);
146 |
147 | ColorWithImplicitParse b = "red";
148 | Assert.AreEqual(b, ColorWithImplicitParse.Red);
149 | }
150 |
151 | [TestMethod]
152 | public void ParseTest_ReferenceEquals()
153 | {
154 | var a = (ColorWithImplicitParse)"red";
155 | var b = ColorWithImplicitParse.Parse("red", false);
156 | var c = ColorWithImplicitParse.Parse("Red", true);
157 | var d = ColorWithImplicitParse.Red;
158 |
159 | Assert.IsTrue(object.ReferenceEquals(a, b));
160 | Assert.IsTrue(object.ReferenceEquals(a, c));
161 | Assert.IsTrue(object.ReferenceEquals(a, d));
162 | }
163 |
164 | [TestMethod]
165 | [ExpectedException(typeof(InvalidOperationException))]
166 | public void ParseTest_CaseInsensitiveShouldFail()
167 | {
168 | ColorWithImplicitParse a = ColorWithImplicitParse.Parse("not a color");
169 | }
170 |
171 | [TestMethod]
172 | [ExpectedException(typeof(InvalidOperationException))]
173 | public void ParseTest_CaseSensitiveShouldFail()
174 | {
175 | ColorWithImplicitCreate a = ColorWithImplicitCreate.Parse("red", true);
176 | }
177 |
178 | [TestMethod]
179 | public void AnyString_OK()
180 | {
181 | ColorWithImplicitCreate myColor = "Red";
182 | Assert.IsTrue("Red" == myColor);
183 | Assert.IsTrue("Red".Equals(myColor));
184 |
185 | myColor = (ColorWithImplicitCreate)"KindaViolet";
186 | Assert.IsTrue("KindaViolet" == myColor);
187 | }
188 | }
189 | }
190 |
--------------------------------------------------------------------------------