Get enum int value by string - c#

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

Related

Reference several class members

I want to access three members of a class (_orderDay, _orderCustody, _orderBox) according to and indexing variable (orderIndex), using a different approach than in the following example
public class COrdering
{
private int _orderDay;
private int _orderCustody;
private int _orderBox;
public COrdering() { _orderDay = _orderCustody = _orderBox = 0; }
public int IncOrder(int orderIndex)
{
int v = orderIndex == 0 ? _orderDay : (orderIndex == 1 ? _orderCustody : _orderBox);
v++;
if (orderIndex == 0) _orderDay = v
else if (orderIndex == 1) _orderCustody = v;
else _orderBox = v;
return v;
}
}
The idea is to use less coding than in the previous example. When I coded something like this in C++ I used std::bind to create a const array of references to each field involved, but I don't know how to make something similar in C#. Can anyone help me out with this?
EDIT
I've found a way to optimize IncOrder method:
//...
private int _incDay() { return ++_orderDay; }
private int _incCustody() { return ++_orderCustody; }
private int _incBox() { return ++_orderBox; }
private IReadOnlyList<Func<int>> _funcs = Array.AsReadOnly(new Func<int>[] {_incDay, _incCustody, incBox});
public int IncOrder(int orderIndex) { return _funcs[orderIndex](); }
There may be another way, such as creating an array of references to these fields, but I don't know if that's possible.
Sounds like a job for an index operator overload:
public int this[int index] => IncOrder(index);
Usage:
COrdering ordering = new COrdering();
int newValue = ordering[0];
Updated - you can use an array internally
public class COrdering
{
public enum OrderIndex { Day = 0, Custody = 1, Box = 2, NumElements };
private readonly int[] values = new int[(int)OrderIndex.NumElements];
public int IncOrder(OrderIndex orderIndex) => ++values[(int)orderIndex];
public int this[OrderIndex index] => IncOrder(index);
}
Also, your constructor can be removed, in C# everything is auto initialized to 0 (or null for reference types).
Why not use a Dictionary<int, int>?
public class COrdering
{
Dictionary<int, int> map = new Dictionary<int, int>();
public COrdering() { map[0] = 0; map[1] = 0; map[2] = 0; }
public int IncOrder(int orderIndex)
{
return ++map[orderIndex];
}
}
In fact you can even use an int[] or a List<int>.
I understand you want to simplify your code, so in that case start by the variables where you save data, if you are accessing them by index it would make more sense to declare an array and use an enum, something like this:
public class COrdering
{
enum OrderType
{
Day = 0,
Custody = 1,
Box = 2,
Count = 3
};
private int[] _order = new int[(int)OrderType.Count];
public int IncOrder(OrderType orderIndex)
{
// Increment corresponding order type and return its value
return ++_order[(int)orderIndex];
}
}
You can see that you implement your IncOrder with just one line of code. The ++ must be before the variable name, so you get the correct answer. I either use an intermediate variable for the increment or a ++ preceded of a good comment, so that the next programmer will see it.
The other solution with [] overload is unexpected and surprising for the next guy debugging your code :-) so that being said I suppose you guess which one I'd chose.

Enum boolean in C#

I have this method
public enum Values
{
True= true,
False=false
};
public static string GetValues(bool values)
{
string status = "";
switch (values)
{
case(bool)UIHelper.Values.False:
}
}
I want to have this enum as boolean. It says, that:
Values cannot be casted as bool.
How can I do it so I can have it boolean?
Of course, you can map to 0 (Service) and 1 (Serial), but why map to that in the first place? Why not use bool from the start?
public static class UnlPointValues
{
public const bool Serial = true;
public const bool Service = false;
}
public static string GetUnloadingPointValues(bool values)
{
string status = "";
switch (values)
{
case UIHelper.UnlPointValues.Serial:
}
}
I don't see that you need an enum here.
public static string GetUnloadingPointValues(bool isSerial)
{
return isSerial ? "Serial" : "Service";
}
Or whatever string values you want to map.
If you have to stick to enum you can implement an extension method:
public enum Values {
True,
False,
// and, probably, some other options
};
public static class ValuesExtensions {
public static bool ToBoolean(this Values value) {
// which options should be treated as "true" ones
return value == Values.False;
}
}
...
// you, probably want to check if UIHelper.Values is the same as values
if (values == UIHelper.Values.ToBoolean()) {
...
}
Use 0 for false and 1 for true instead combined with Convert.ToBoolean
true if value is not zero; otherwise, false.
public enum UnlPointValues
{
Serial = 1, //true
Service = 0 //false
};
public static string GetUnloadingPointValues(bool values)
{
string status = "";
switch (values)
{
case (Convert.ToBoolean((int)UIHelper.UnlPointValues.Serial)):
break;
case (Convert.ToBoolean((int)UIHelper.UnlPointValues.Service)):
break;
}
}

Advice - How to implement the same code with different parameters

I would like an advice. My project have a lot of equals methods with different values, and i would like to do a single method that does the same.
The methods are this:
private void Enum1()
{
Console.WriteLine(Enum.GetValue(ENUM1.Code));
Console.WriteLine(Enum.GetValue(ENUM1.Info));
}
private void Enum2()
{
Console.WriteLine(Enum.GetValue(ENUM2.Code));
Console.WriteLine(Enum.GetValue(ENUM2.Info));
}
private void Enum3()
{
Console.WriteLine(Enum.GetValue(ENUM3.Code));
Console.WriteLine(Enum.GetValue(ENUM3.Info));
}
This is the enums:
public enum ENUM1
{
Code = 1,
Info = 3
}
public enum ENUM2
{
Code = 91,
Info = 4
}
public enum ENUM3
{
Code = 6,
Info = 27
}
There is only a way to create a method by inserting the input type of enum to use? maybe a similar solution of this:
private void General("ENUM1")
{
var type = ENUM1;
switch (p)
{
case "ENUM1":
type = ENUM1;
case "ENUM2":
type = ENUM2;
case "CASALINGHI":
type = ENUM3;
default:
type = ENUM1;
}
Console.WriteLine(Enum.GetValue(type.Code));
Console.WriteLine(Enum.GetValue(type.Info));
}
I think something like this is what you are looking for:
private void General<T>()
{
var values = Enum.GetValues(typeof(T));
foreach(var value in values)
Console.WriteLine(value);
}
General<Enum1>();
General<Enum2>();
General<Enum3>();
Or this, depending on how you want to use it:
private void General(Type enumType)
{
var values = Enum.GetValues(enumType);
foreach(var value in values)
Console.WriteLine(value);
}
General(typeof(Enum1));
General(typeof(Enum2));
General(typeof(Enum3));
Why do you keep using enums, when you can easily use classes? Read more about Object-Oriented programming.
Create a single class:
public class MyEnum
{
public int Code
{
get; set;
}
public int Info
{
get; set;
}
public string Display()
{
Console.WriteLine(this.Code);
Console.WriteLine(this.Info)
}
//
// This will keep your enums static, available from any method
//
private static List<MyEnum> _globals = new List<MyEnum();
public static List<MyEnum> Globals ()
{
if (this._globals.Count == 0)
{
this._globals.Add(new MyEnum(){ Code = 1, Info = 3 });
this._globals.Add(new MyEnum(){ Code = 91, Info = 4 });
this._globals.Add(new MyEnum(){ Code = 6, Info = 27 });
}
return this._globals;
}
}
After this you can easily print out all the enums with the following code:
foreach (MyEnum* en in MyEnum.Globals())
{
en.Display();
}
Please look into solutions similar to this one, since your enum's obviously represent some data.

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;
}

C# get/set solution

To give some background I'm trying to solve the Project Euler Problem 54 involving poker hands. Though there's infinite approaches to this. What I would like to do is enumerate through a list of strings, for example:
{ "8C", "TS", "KC", "9H", "4S" };
I would like to "get" an instance of class card with properties value, and suit, for each respective string. I've not yet utilized get/set so maybe there is an obvious approach to this I'm missing.
Ultimately I would like to have a list of objects type Card, I don't mind building all the card's ahead of time, such that "2H" returns an instance of type Card where suit = Hearts, and value = 2, for example.
I know this code is wrong, but it should give an idea of what I'm trying to do. Any suggestions would be appreciated.
class Card
{
public string suit;
public int value;
public string cardname
{
get
{
if (cardname == "2H") Card TwoH = new Card();
TwoH.suit = "Hearts"
TwoH.value = 2;
return TwoH;
}
}
}
Why not make a constructor that fills suit and value based on a string parameter
public Card(string name)
{
switch(name)
{
case "2H":
this.suit = "Hearts";
this.value = 2;
break;
//...
}
}
This might not be the exact solution you seem to be asking for but if the values you'll be getting (eg 2H, 3C etc) are all 2 characters long, then you can try this:
public class Card
{
public string suit { get; set; }
public int value { get; set; }
public static Card GetCard(string cardName)
{
string tmpSuit;
int tmpValue;
char[] cardNameParts = cardName.ToCharArray();
switch(charNameParts[0])
{
case "A":
tmpValue = 1;
break;
case "2":
tmpValue = 2;
break;
...
}
switch(charNameParts[1])
{
case "H":
tmpSuit= "Hearts";
break;
case "C":
tmpSuit= "Clubs";
break;
...
}
return new Card() { suit = tmpSuit, value = tmpValue };
}
}
I would do it like that:
public class Card
{
public string Suit { get; set; }
public int Value { get; set; }
public static Card FromString(string s)
{
if (s == "2H") return new Card() { Suit = "Hearts", Value = 2 };
else if (s == "....")
...
else return null;
}
}
I have converted your suit and value field into properties and instead of some getter method which in your case wouldn't work I have added a static method.
You can use it like this Card card2H = Card.FromString("2H");
Maybe use two switch statements, first
switch (cardname[0])
{
...
}
then
switch (cardname[1])
{
...
}
Before that, check that cardname.Length == 2. In each switch, have a default section where you throw an exception in case the char value doesn't make sense.

Categories

Resources