Enum not default to 0 when not defined - c#

I have an enum type defined as follows:
public enum OperationTypeEnum : byte
{
/// <remarks/>
#__NONE = 0,
/// <remarks/>
Sale = 1,
/// <remarks/>
Auth = 2
}
In my code, I cast an integer like so:
var operationType = (OperationTypeEnum) anotherIntVariable;
When anotherIntVariable is something undefined (e.g. 5), I am hoping to get 0 or __NONE back (since 5 is not defined as one of the valid enum values, but I receive 5 instead.
What do I need to change to make undefined enum values to be 0?
Thanks!

The answer was given by #plast1k.
Here is a generic extension for your problem
public static class OperationTypeEnumExtensions
{
public static T ToEnum<T>(this byte val) where T : struct
{
if(Enum.IsDefined(typeof(T), val))
return (T) Enum.Parse(typeof(T), val.ToString());
return default(T);
}
}
usage
value.ToEnum<OperationTypeEnum>()

C# enums are effectively integers and there are no compile or run time checks that you are using a "valid" value from your defined enum set. See this answer for more information https://stackoverflow.com/a/6413841/1724034

If you get a numerical value and need to only get actual enum values, you can use Enum.TryParse
The example displays the following output:
Converted '0' to None.
Converted '2' to Green.
8 is not an underlying value of the Colors enumeration.
blue is not a member of the Colors enumeration.
Converted 'Blue' to Blue.
Yellow is not a member of the Colors enumeration.
using System;
[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
public class Example
{
public static void Main()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
Colors colorValue;
if (Enum.TryParse(colorString, out colorValue))
if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
else
Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
}
}
}

The safest method is to create an extension method for your enum class that will compare the enum values and if none of them initialize to #__NONE
If you are certain there are only a limited amount of enum values:
public static class OperationTypeEnumExtensions
{
public static OperationTypeEnum ToOperationTypeEnum(this int val)
{
switch (val)
{
case (int) OperatinTypeEnum.Sale:
return OperationTypeEnum.Sale;
cast (int) OperationTypeEnum.Auth:
return OperationTypeenum.Auth;
default:
return OperationTypeEnum.#_none;
}
}
}
Usage:
int myInt = GetMyIntValue();
OperationTypeEnum myEnum = myInt.ToOperationTypeEnum();

#If your enum class is defined as below.
public enum CategoryEnum : int
{
Undefined = 0,
IT= 1,
HR= 2,
Sales= 3,
Finance=4
}
Now if you want to find Undefined enum if value doesnot match 1,2,3,4 then using the following Enum.IsDefine() function
Enum.IsDefined(typeof(CategoryEnum), request.CategoryId)
#returns true if id matches any enum values
#else returns false
Now for parsing the enum values as string
public enum Mode
{
UNDEFINED = 0,
APP = 1,
TEXT = 2,
}
var value = Enum.TryParse(request.Mode, true, out Mode mode);
#returns mode enum
#Now to get Corresponding value for id or vice-vera, have an extension method as below:
public static T AsEnum<T>(this string input) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
Enum.TryParse(input, ignoreCase: true, out T result);
return (T)result;
}
Then fetch it using AsEnum() function:
var status = searchText.AsEnum<StatusEnum>();

Related

Get enum value as string

I have an enum like this:
enum myEnum
{
a = 0101,
b = 2002,
c = 0303
}
I try to get enum value with casting but the 0 at the begin of my enums was removed.
For example I tried this:
var val = (int)myEnum.a;
How can get enum value as string when we have 0 at the beginning of it?
You should rethink your design, but if you want to check your enum integers to a given string, you can use .ToString("0000") to get the string "0101" out of the integer 101.
First, enums are integers, since as their name says, they are enumerations and an enumeration, they are numbers, so enum is integer.
Secondly, you must bear in mind that zero is a null value, since the system is a 01 or 001 like 1, since (basic mathematics) a zero to the left is worthless, so this code is incorrect.
enum myEnum
{
a=0101,
b=2002,
c=0303,
}
The correct way is
enum myEnum
{
a = 0,
b = 1,
c = 2
}
Where the zero is alone, so the system sees it as an index
Now with this, you should only use one of the conversion processes of C#
string strOne = ((myEnum)0).ToString();
string strTwo = ((myEnum)1).ToString();
string strThree = ((myEnum)2).ToString();
Read the MSDN reference https://msdn.microsoft.com/en-us/library/16c1xs4z(v=vs.110).aspx
Enumeration values are always integers. If you need to associate a string with an enumeration value, you can use a dictionary:
enum myEnum { a, b, c }
Dictionary<myEnum, string> lookup = new Dictionary
{
{ a, "0101" },
{ b, "2002" },
{ c, "0303" }
};
To get the string associated with a particular value just use this:
var s = lookup[myEnum.a]; // s = 0101
Another common way to handle this sort of problem is simply to use constants.
class MyConstants
{
public const string a = "0101";
public const string b = "2002";
public const string c = "0303";
}
var s = MyConstants.a; // s = 0101
Try using formatting: you want 4 digits and that's why you can put d4 format string. In order to hide all these implmentation details (cast and formatting) let's write an extension method:
enum myEnum {
a = 0101,
b = 2002,
c = 0303
}
static class myEnumExtensions {
public static string ToReport(this myEnum value) {
return ((int)value).ToString("d4"); // 4 digits, i.e. "101" -> "0101"
}
}
...
myEnum test = myEnum.a;
Console.Write(test.ToReport());
If you always need a specific number of digits you could use string format to get the leading zeros:
var str = String.Format("{0:0000}", (int)myEnum.a);
Or, shorter:
var str = $"{(int) myEnum.a:D4}";
Alternative:
Use an attribute to add extra information to an enum
Attribute:
public class DescriptionAttribute : Attribute
{
public string Name { get; }
public DescriptionAttribute(string name)
{
Name = name;
}
}
Enum:
enum myEnum
{
[Description("0101")]
a = 101,
[Description("2002")]
b = 2002,
[Description("303")]
c = 303
}
Extension Method:
public static string GetDescription(this myEnum e)
{
var fieldInfo = e.GetType().GetField(e.ToString());
var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
return attribute.Name;
}
Usage:
var name = myEnum.a.GetDescription() //will return '0101'
Assuming that the numbers in your enum always have a length of 4
you can use the following
var val = (int)myEnum.a).ToString().PadLeft(4, '0')

sign value from combobox with enum to another class

Im trying to sign a selected value from a combobox that holds enum values.
this is where i fill the combobox
cmbPrio.Items.AddRange(Enum.GetNames(typeof(PriorityType.Prioritytypes)));
cmbPrio.SelectedIndex = (int) PriorityType.Prioritytypes.Normal;
This is where im tryingt to set the value in my class
private void ReadInput()
{
if (String.IsNullOrEmpty(txtTodo.Text))
{
MessageBox.Show("Write something to do!");
}
else
{
currTasks.Priority = what code should go here??!
currTasks.Description = txtTodo.Text;
currTasks.TaskDate = dateTimePickerToDo.Value;
}
}
My class with the enum:
class PriorityType
{
public enum Prioritytypes
{
Very_Important,
Important,
Normal,
Less_Importan
}
}
My class where my get:set is:
private PriorityType priority;
public PriorityType Priority
{
get
{
return this.priority;
}
set
{
this.priority = value;
}
}
Fill the cmbPrio with enum values directly:
cmbPrio.Items.AddRange(Enum.GetValues(typeof(Prioritytypes)).Cast<object>().ToArray());
So you can assign it as enum value:
currTasks.Priority = (Prioritytypes)cmbPrio.SelectedItem;
This will also work if SelectedIndex doesn't correspond to the int value behind your enum type, e.g.
public enum Prioritytypes
{
Very_Important = 1,
Important = 2,
Normal = 4,
Less_Importan = 8
}
or if you change the order of entries in your combobox.

Enum as parameter: Get name and index

I have an enum like this:
public enum Global
{
txt_test = 123
}
Now I want to use a call like this:
var text = lib.Get(Global.txt_test);
Method:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = ?; // (int)enumeration not working
...
}
How to get the index of an enum in this case?
Or am I doing it wrong at all?
Thank you.
Solution:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = Convert.ToInt32(enumeration);
...
}
Enum are convertible to int for retrieving their values:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = Convert.ToInt32(enumeration);
// ...
return null;
}
Note that this will work because your enumeration is type of int by default. Enums can still be other value type like long :
enum Range : long { Max = 2147483648L, Min = 255L };
In this case, the conversion will lost precision.
If you only need the enum value (what you are calling "index") as a string, the best way is to use custom format strings as documented here: http://msdn.microsoft.com/en-us/library/c3s1ez6e%28v=vs.110%29.aspx
For example:
public TextString Get(Enum enumeration)
{
string index = enumeration.ToString("D");
// ...
return null;
}

Get enum int value by string

I have implemented the enum below:
public enum CaseOriginCode
{
Web = 0,
Email = 1,
Telefoon = 2
}
I would like to get the enum int value by a string. Something like this:
public void setCaseOriginCode(string caseOriginCodeParam)
{
int caseOriginCode = CaseOriginCode.GetEnumByString(caseOriginCodeParam);
// do something with this integer
}
So my input is a string and my output needs to be an int.
Or is it better to implement an dictionary with an key value. The key will be the string and the will be an int.
Please try with the below code snippet.
public void setCaseOriginCode(string CaseOriginCode)
{
int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}
Let me know if any concern.
One thing to note, if after casting you are getting a result of 0, then it is likely because you did not specify a value for your enum.
For example, change this:
public enum AcquisitionChannel
{
Referal,
SearchEngines,
SocialMedia
}
to
public enum AcquisitionChannel
{
Referral = 1,
SearchEngines = 2,
SocialMedia = 3
}
If I understand this question correctly why not just use a switch case?
public CaseOriginCode setCaseOriginCode(string caseOriginCodeParam)
{
switch(caseOriginCodeParam)
{
case "Web":
return CaseOriginCode.Web;
case "Email":
return CaseOriginCode.Email;
case "Telefoon":
return CaseOriginCode.Telefoon;
default:
return default(CaseOriginCode);
}
}
So in practice it would be something like this...
int x = (int)setCaseOriginCode("Web"); // output would be 0
CaseOriginCode y = setCaseOriginCode("Email"); // output would be CaseOriginCode.Email

How to sum two objects?

I want to do an application that pareses text. So far, I have a class called Result, that holds the value and type each part of an equation.
public enum ResultType
{
Int32,
Double,
Boolean,
Color,
DateTime,
String,
Undefined,
Void
}
public class Result
{
public object Value { get; set; }
public ResultType Type { get; set; }
}
Possible Result's could be:
5 : Int32
true : Boolean
DADACC : Color
"Hello World!" : String
10.0 : Double
13/11/1986 : DateTime
Now I want to sum/divide/pow/... two Results but I really don´t want to do all the work. In C#, you can mix them all together and get an answer.
var value = "Hello" + 2.0 + 4 + DateTime.Today; (value = "Hello2413/09/2011 12:00:00 a.m.")
Is there an easy way to handle this? Or do I have to figure out all combos by myself? I´m thinking about something like:
var Operator = "+"; // or "-","*","/","^","%"
var sum = DoTheCSharpOperation(Operator, ResultA.Value, ResultB.Value)
var sumResult = new Result(sum);
This sounds to me like a perfect application for the "dynamic" keyword:
using System;
using System.Diagnostics;
namespace ConsoleApplication33 {
public static class Program {
private static void Main() {
var result1=DoTheCSharpOperation(Operator.Plus, 1.2, 2.4);
var result2=DoTheCSharpOperation(Operator.Plus, "Hello", 2.4);
var result3=DoTheCSharpOperation(Operator.Minus, 5, 2);
Debug.WriteLine(result1); //a double with value 3.6
Debug.WriteLine(result2); //a string with value "Hello2.4"
Debug.WriteLine(result3); //an int with value 3
}
public enum Operator {
Plus,
Minus
}
public static object DoTheCSharpOperation(Operator op, dynamic a, dynamic b) {
switch(op) {
case Operator.Plus:
return a+b;
case Operator.Minus:
return a-b;
default:
throw new Exception("unknown operator "+op);
}
}
}
}

Categories

Resources