I have several methods in an application I'm working on loaded with optional parameters, some of which are enums. Currently, in order to do that I'm writing methods with a similar type of signature:
public void SomeMethod(string myFirstParam = "", string mySecondParam = "", MyEnum myThirdParam = (MyEnum )(-1)){
if (myThirdParam != (MyEnum ) (-1))
{
//do something with it
}
}
So my first question is, is there some pitfall to this approach I haven't realized, but in time will become painfully aware of, and secondly, is there a more proper - or at least elegant solution to it?
I should say that we control the input to this method, it's used internally, so I'm not worried about someone casting in a value of -1 to gum up the works.
I would suggest using nullable enum in this situation, like this:
public void SomeMethod(string myFirstParam = "",
string mySecondParam = "",
MyEnum? myThirdParam = null)
{
if (myThirdParam.HasValue)
{
var enumValue = myThirdParam.Value;
//do something with it
}
}
and you can use it like this:
SomeMethod(myThirdParam: MyEnum.Something);
Make sure your enum has a default value (equal to zero), that means "none" or "invalid". This would be an appropriate value for your optional parameter's default value.
This is recommended by Microsoft Code Analysis as well, CA1008: Enums should have zero value.
For example:
enum SpeakerType
{
None = 0,
Woofer,
Midrange
Tweeter
}
This way the default keyword provides a value that is sane, but doesn't unintentionally refer to something you don't want it to.
As an example, the BCL uses this same concept. The number of stop bits to use for a SerialPort is defined by the StopBits enum:
public enum StopBits
{
None,
One,
Two,
OnePointFive,
}
However the None value is invalid. In fact,
The SerialPort class throws an ArgumentOutOfRangeException exception when you set the StopBits property to None.
What about :
enum MyEnum {
MISSING = -1,
FirstValue,
SecondValue,
...
}
public void SomeMethod(string myFirstParam = "", string mySecondParam = "", MyEnum myThirdParam = MISSING) {
if (myThirdParam != MISSING)
{
//do something with it
}
}
Related
I'm working on a game with Unity in which the player has some spells. I have an enum that contains all of these and I want to attach them a bool value. I think I can use a System.Collections.Generics.Dictionary with the Spells as Keys and the Boolean as Value, but is there a simpler way to do such a thing?
You can simplify Dictionary<Spell, bool> hasSpell into HashSet<Spell> (you want only Key, not Value from the initial Dictionary):
public enum Spell {
Fireball,
Levitate,
Resurrect,
};
...
HashSet<Spell> abilities = new HashSet<Spell>() {
Spell.Fireball,
Fireball.Levitate,
};
...
// If the hero can resurrect...
if (abilities.Contains(Spell.Resurrect)) {
// ...let him raises from the dead
}
Individually the simplest way of pairing two data values is to use a value tuple. This feature can be used on any Unity version from 2018.3 onwards as that's when it stopped using outdated C# versions.
var spell = ("Fireball", true);
If you'd rather be more explicit about types:
(string, bool) spell = ("Fireball", true);
(This is another approach in making things "easy")
Yes, dictionnary are simple collections but it's not really what I expect. I want something just to say "this value from the enum is true, this one is false"
This sounds you need a nice class that encapsulates the less-simple or more low-level structure (e.g. dictionary or hashset). This will things easy from the outside / API-isde.
For example:
public enum Spell
{
Firebolt,
Rage,
Flash,
};
public class SpellState
{
private HashSet<Spell> _enabled = new HashSet<Spell>();
public void EnableSpell(Spell spell)
{
_enabled.Add(spell);
}
public void DisableSpell(Spell spell)
{
_enabled.Remove(spell);
}
public bool IsSpellEnabled(Spell spell)
{
return _enabled.Contains(spell);
}
}
Usage
var spellState = new SpellState();
spellState.EnableSpell(Spell.Rage);
// later
if (spellState.IsSpellEnabled(Spell.Flash))
{
spellState.DisableSpell(Spell.Rage);
// todo
}
You could use a single bitwise value by defining enum flags, so long as you have a limited number of spells.
[Flags]
public enum Spell : long
{
Firebolt = (1 << 0),
Rage = (1 << 1),
Flash = (1 << 2),
};
I've got a enum type defined in my C# code that corresponds to all possible values for the NetConnectionStatus field in Win32_NetworkAdapter WMI table, as documented here.
The documentation shows that the integers 0 through 12 each have a unique status name, but then all integers between 13 and 65,535 are lumped into one bucket called "Other." So here's my code:
[Serializable]
public enum NetConnectionStatus
{
Disconnected = 0,
Connecting = 1,
Connected = 2,
Disconnecting = 3,
HardwareNotPresent = 4,
HardwareDisabled = 5,
HardwareMalfunction = 6,
MediaDisconnected = 7,
Authenticating = 8,
AuthenticationSucceeded = 9,
AuthenticationFailed = 10,
InvalidAddress = 11,
CredentialsRequired = 12,
Other
}
This works fine for the values that are not Other. For instance, I can do this:
var result = (NetConnectionStatus) 2;
Assert.AreEqual(NetConnectionStatus.Connected, result);
But for anything in that higher numeric range, it doesn't work so great. I would like it if I could do this:
var result = (NetConnectionStatus) 20;
Assert.AreEqual(NetConnectionStatus.Other, result);
But right now that result variable gets assigned the literal value 20 instead of Other. Is there some out-of-the-box way of accomplishing this, something akin to Parse() but for integers instead of strings, or perhaps some special attribute I'm unaware of? I would prefer to not write my own wrapper method for this if there is already a good way to accomplish this.
If you have a string value, then the closest thing I can think of is to use Enum.TryParse:
NetConnectionStatus result;
if (Enum.TryParse(stringValue, out result) == false)
result = NetConnectionStatus.Other;
For an integer value that you're casting, you can use:
result = (NetConnectionStatus)integerValue;
if (Enum.GetValues(typeof(NetConnectionStatus)).Contains(result) == false)
result = NetConnectionStatus.Other;
Not really ideal, but in C# enums aren't much more than fancy names for integral values, so it's valid to stuff an integer value not in the defined values of the enums into a value of that enum type.
This solution will handle negative numbers, or cases where you have gaps in your enum values more elegantly than doing numerical comparisons.
it would be nice but no. How about
var result = (NetConnectionStatus) 20;
Assert.IsTrue(result >= (int)NetConnectionStatus.Other);
.NET does not such thing as a "any other" enumeration value bucket. Technically, enumeration (enum) is a pretty set of named constants of some underlying type (which is one of following: sbyte, short, int, long and their unsigned counterparts). You can cast an enum value to/from a corresponding type without any losses, as in this example:
enum TestEnum:int // Explicitly stating a type.
{
OnlyElement=0
}
class Program
{
static void Main(string[] args)
{
// Console.WriteLine implicitly calls ToString of the TestEnum.OnlyElement.
Console.WriteLine("OnlyElement == {0}", TestEnum.OnlyElement);
//TestEnum.OnlyElement equals to 0, as demonstrated by this casting:
Console.WriteLine("(int)OnlyElement == {0}", (int)TestEnum.OnlyElement);
//We can do it in reverse...
Console.WriteLine("(TestEnum)0 == ",(TestEnum)0);
// But what happens when we try to cast a value, which is not
// representable by any of enum's named constants,
// into value of enum in question? No exception is thrown
// whatsoever: enum variable simply holds that value, and,
// having no named constant to associate it with, simply returns
// that value when attempting to "ToString"ify it:
Console.WriteLine("(TestEnum)5 == {0}", (TestEnum)5); //prints "(TestEnum)5 == 5".
Console.ReadKey();
}
}
I'd like to repeat it again, enum in .NET is simply a value of the underlying type with some nice decorations like overriden ToString method and flags checking (look here or here if you want to know more about flags). You cannot have an integer with only 14 values like "0..12 and everything else", and so you cannot have such enum. In your example, NetConnectionStatus.Other simply receives single literal value (I assume it would most probably be '13', as the next available positive value of underlying type - however it actually depends on the compiler) as any other enumeration constant would do if not specified explicitly - and, obviously, it does not become a bucket.
However, there are options to achieve simple equation checks for integers/bytes/shorts/longs - and enums alike. Consider this extension method:
static bool IsOther(this NetConnectionStatus A)
{
return (A < (NetConnectionStatus)0) || (A > (NetConnectionStatus)12);
}
Now you can have a simple assertion like this:
var result = (NetConnectionStatus)10;
Trace.Assert(result.IsOther()); //No assertion is triggered; result is NetConnectionStatus.AuthenticationFailed
and
var result = (NetConnectionStatus)20;
Trace.Assert(result.IsOther()); //Assertion failed; result is undefined!
(Of course you can replace IsOther method with IsNotOther, overload it and pretty much anything else you could do with a method.)
Now there is one more thing. Enum class itself contains a method called IsDefined, which allows you to avoid checks for specific enum's value boundaries (<0, >12), therefore preventing unwanted bugs in case enum values would ever be added/removed, at the small performance cost of unboxing and checking each value in enum for a match (I'm not sure how this works under the hood though, I hope these checks are optimized). So your method would look like this:
static bool IsOther(NetConnectionStatus A)
{
return !Enum.IsDefined(typeof(NetConnectionStatus), A);
}
(However, concluding from enum's name, it seems like you want to make a network application/server, and for these performance might be of very great importance - but most probably I'm just being paranoid and this will not be your application's bottleneck. Stability is much more of concern, and, unless you experience real troubles with performance, it is considered to be much better practice to enable as much stability&safety&portability as possible. Enum.IsDefined is much more understandable, portable and stable than the explicit boundaries checking.)
Hope that helps!
Thanks everyone for the replies. As confirmed by all of you, there is indeed no way to do this out-of-the-box. For the benefit of others I thought I'd post the (custom) code I ended up writing. I wrote an extension method that utilizes a custom attribute on the enum value that I called [CatchAll].
public class CatchAll : Attribute { }
public static class EnumExtensions
{
public static T ToEnum<T, U>(this U value) where T : struct, IConvertible where U : struct, IComparable, IConvertible, IFormattable, IComparable<U>, IEquatable<U>
{
var result = (T)Enum.ToObject(typeof(T), value);
var values = Enum.GetValues(typeof(T)).Cast<T>().ToList();
if (!values.Contains(result))
{
foreach (var enumVal in from enumVal in values
let info = typeof(T).GetField(enumVal.ToString())
let attrs = info.GetCustomAttributes(typeof(CatchAll), false)
where attrs.Length == 1
select enumVal)
{
result = enumVal;
break;
}
}
return result;
}
}
So then I just have to apply that [CatchAll] attribute to the Other value in the enum definition. Then I can do things like this:
int value = 13;
var result = value.ToEnum<NetConnectionStatus, int>();
Assert.AreEqual(NetConnectionStatus.Other, result);
And this:
ushort value = 20;
result = value.ToEnum<NetConnectionStatus, ushort>();
Assert.AreEqual(NetConnectionStatus.Other, result);
This question already has answers here:
Enum from string, int, etc
(7 answers)
Closed 8 years ago.
I am working on WCF service and want to return preference key as enum rather than string.
How to make enum of preferencekey column which is string type in best optimized way?
You should use the enum.Parse Method:
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), enumString);
I found the code snippet.
Rohit,
The value of preferenceKey could not easily be converted to an enum as you would expect. The strings could be parsed using Enum.Parse() method however the enum names must be different than what you have in the database. The problems are
Your string starts with a number
Your string contains the - characters
Now that being said you could design a different approach to your naming convetion of an enum as an example (I dont like this example personally but might work).
First define a new attribute called EnumName this attribute will be used to decorate your enums with the name that you expect from the database. Such as
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
public sealed class EnumNameAttribute : Attribute
{
readonly string name;
public EnumNameAttribute(string name)
{
this.name = name;
}
public string Name { get { return this.name; } }
}
The next step will be to define your enums (what I dont like is the names)
public enum Preferences
{
[EnumName("6E-SF-TYPE")]
SIX_E_SF_TYPE = 0,
[EnumName("6E-SF-VALUE")]
SIX_E_SF_VALUE = 1
}
Simple enough, we have our enum with each item decorated with the EnumName attribute. The next step will be to create a method to parse the enum based on the string from the database.
public static class EnumNameParser
{
public static Preferences ParseString(string enumString)
{
var members = typeof(Preferences).GetMembers()
.Where(x => x.GetCustomAttributes(typeof(EnumNameAttribute), false).Length > 0)
.Select(x =>
new
{
Member = x,
Attribute = x.GetCustomAttributes(typeof(EnumNameAttribute), false)[0] as EnumNameAttribute
});
foreach(var item in members)
{
if (item.Attribute.Name.Equals(enumString))
return (Preferences)Enum.Parse(typeof(Preferences), item.Member.Name);
}
throw new Exception("Enum member " + enumString + " was not found.");
}
}
This method simply takes an input stream, evaluates all the EnumNameAttributes and returns the first match (or exception if not found).
Then this can be called such as.
string enumString = "6E-SF-TYPE";
var e = EnumNameParser.ParseString(enumString);
Now if you want to take the enum and get the name for the database you can extend your helper method with
public static string GetEnumName(this Preferences preferences)
{
var memInfo = typeof(Preferences).GetMember(preferences.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumNameAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((EnumNameAttribute)attrs[0]).Name;
}
throw new Exception("No enum name attribute defined");
}
I really would recommend storing the numerical values rather than the text values in the database. If you want the text values in the database too then add a table for it. Regardless, the Enum.Parse and .TryParse methods will convert a String and the .ToObject method will convert either text or numbers.
How to make enum of preferencekey column which is string type in best optimized way
Well i am afraid you cannot use your preference key as enum for 2 reasons.
your preference key is starting with integer values making it an in-valid identifier.
it also contains - which is not allowed either.
However, if you are able to convert your preference key to some valid identifiers then you can do this.
i would recomment using Enum.TryParse for parsing because
TryParse(String, Boolean, TEnum) is identical to the Parse(Type, String, Boolean) method, except that instead of throwing an exception, it returns false if the conversion fails. It eliminates the need for exception handling when parsing the string representation of an enumeration value.
Something like this
string testingString = "Test1";
SomeEnum result;
if (Enum.TryParse(testingString, out result))
{
Console.WriteLine("Success");
}
or if case sensitivity doesn't matter to you. Then you can use the overload like this
if (Enum.TryParse(testingString,true, out result))
Console.WriteLine("Success");
where SomeEnum is
public enum SomeEnum
{
Test1 = 1,
Test2 = 2
}
The simples way to do this would be:
1) create an enum representing all possible preference key values, but add a 'invalid' with value -1.
enum PreferenceKey
{
INVALID = -1,
SIX_E_SF_TYPE = 0,
SIX_E_SF_VALUE = 1,
...
}
2) create a list of strings containing the string representations of all preference key values in the same order as the enum.
private List<string> strings = new List<string> {"6E-SF-TYPE", "6E-SF-VALUE", ...};
3) Lookup the column value in the list of strings and cast the position to the enum.
If the column value cannot be found in the list of strings, IndexOf will return -1, which is the 'invalid' value.
PreferenceKey key = (PreferenceKey) strings.IndexOf(preferenceKeyColumnValue);
How can I effective extend enum to have more than 2 options.
I am reading events from a file, line-by-line.
I have a constructor
public enum EventType
{ A,D }
public class Event
{
public EventType Type { get; set; }
}
I assigned Type property like this:
Type = tokens[2].Equals("A") ? EventType.A : EventType.D,
where token[2] is the string that holds values like "A".
This works fine when there are only A and D, but I want to have 2 more types; say R and C. When I add them to enum field, how can I get the type? The above is giving compilation errors as if using Type as a variable.
I appreciate your immediate help!
Thanks
There are really only three sensible ways to go about this:
Enum.TryParse
If the tokens will always correspond exactly to your enum members, you can use Enum.TryParse:
EventType type;
if (Enum.TryParse(tokens[2], out type)) {
Type = type;
}
else { /* token does not exist as an enum member */ }
This approach is the simplest, but it's probably slower than the next one and it also has another drawback: the author of the code that provides tokens[2] and the author of the enum must always keep their code in sync.
Use a dictionary
var dict = new Dictionary<string, EventType>
{
{ "A", EventType.A },
{ "D", EventType.D },
// more items here
}
Type = dict[tokens[2]]; // no error checking, please add some
This requires some setup, but it's probably the fastest and it also allows accounting for changes in the input strings and/or enum values.
Use an attribute
Alternatively, you can annotate your enum members with a custom attribute and write a helper method that uses reflection to find the correct member based on the value of this attribute. This solution has its uses but it's the least likely candidate; most of the time you should prefer one of the two alternatives.
You can want to use Enum.Parse to get the matching value:
Type = Enum.Parse(typeof(EventType), tokens[2])
If tokens[2] is not defined in EventType, Enum.Parse throws an exception, so you can use Enum.IsDefined to check if there is an enum value for the string:
Enum.IsDefined(typeof(EventType), tokens[2])
You may use Enum.Parse to parse a string. For error handling you may use Enum.GetNames(typeof(EventType)) and iterate over the returned string array, which contains all possible names of the enum.
var type = (EventType)Enum.Parse(typeof(EventType), tokens[2]);
EventType et;
switch(tokens[2])
{
case "A":
et=EventType.A;
break;
case "B":
et=EventType.B;
break;
case "C":
et=EventType.C;
break;
}
return et;
I want to check that some integer type belongs to (an) enumeration member.
For Example,
public enum Enum1
{
member1 = 4,
member2 = 5,
member3 = 9,
member4 = 0
}
Enum1 e1 = (Enum1)4 gives me member1
Enum1 e2 = (Enum1)10 gives me nothing and I want to check it.
Use Enum.IsDefined
Enum.IsDefined(typeof(Enum1), 4) == true
but
Enum.IsDefined(typeof(Enum1), 1) == false
As Sam says, you can use IsDefined. This is somewhat awkward though. You may want to look at my Unconstrained Melody library which would let you us:
Enum1 e2 = (Enum1)10;
if (e2.IsNamedValue()) // Will return false
{
}
It's probably not worth it for a single enum call, but if you're doing a lot of stuff with enums you may find some useful things in there.
It should be quicker than Enum.IsDefined btw. It only does a linear scan at the moment, but let me know if you need that to be improved :) (Most enums are small enough that they probably wouldn't benefit from a HashSet, but we could do a binary search...)
int testNum = 5;
bool isMember = Enum.GetValues(typeof(Enum1)).Cast<int>().Any(x => x == testNum);
You look through the values of the enum and compare them to the integer.
static bool EnumTest(int testVal, Enum e)
{
bool result = false;
foreach (var val in Enum.GetValues(typeof(Enum1)))
{
if ((int)val == testVal)
{
result = true;
break;
}
}
return result;
}
Edit: Looks like Sam has a better solution.
You can use Enum.GetValues to get all defined values. Then check if your value exists in that list.
http://msdn.microsoft.com/en-us/library/system.enum.getvalues.aspx
Be careful this won't work if you have an enum for 3 (Apples and Pears) the methods above won't detect it as valid.
[Flags]
public enum Fruit
{
Apples=1,
Pears=2,
Oranges =4,
}
Here's a succinct little snippet from an extension method I wrote a few years ago. Combines TryParse with IsDefined to do it all in one swoop and handle values that don't exist in the enum.
if (value != null)
{
TEnum result;
if (Enum.TryParse(value.ToString(), true, out result))
{
// since an out-of-range int can be cast to TEnum, double-check that result is valid
if (Enum.IsDefined(typeof(TEnum), result.ToString() ?? string.Empty))
{
return result;
}
}
}
Here's the extension for integer values
public static TEnum ParseToEnum<TEnum>(this int value, TEnum? defaultValue = null, bool useEnumDefault = false) where TEnum : struct
{
return ParseToEnumInternal(value, defaultValue, useEnumDefault);
}
And a usage
public enum Test
{
Value1 = 1,
Value2 = 3
}
var intValue = 1;
var enumParsed = intValue.ParseToEnum<Test>(); // converts to Test.Value1
intValue = 2;
enumParsed = intValue.ParseToEnum<Test>(); // either throws or converts to supplied default
enumParsed = 3.ParseToEnum<Test>(); // converts to Test.Value2
Some people don't like how it dangles off the end of the (potentially nullable) value, but I have an extension that handles null values of nullable types (int?) and I like it myself, so ...
I can post like a Gist of the whole extension method with all the overloads if you're interested.
Use:
if (Enum.IsDefined(typeof(Fruit),e2))
{
//Valid Value
}
else
{
//Invalid ENum Value
}
Found this useful. https://stackoverflow.com/a/64374930/16803533
no need to use IsDefined and No range checking