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;
}
}
Related
Can I make an alias for enum value name in C# ?
For example I have two files: A and B.
public class A
{
public enum myEnum
{
value_1,
value_2
};
}
And I want to use this enum in B class:
public class B
{
private A.myEnum[] tab = { A.myEnum.value_1, A.myEnum.value_2, A.myEnum.value_1 ..}
}
I want to make an alias for:
A.myEnum.value_1 and A.myEnum.value_2
so I could write
private A.myEnum[] tab = { alias_1, alias_2},
I think I might be missing something, but:
public class B
{
private const A.myEnum alias_1 = A.myEnum.value_1;
private const A.myEnum alias_2 = A.myEnum.value_2;
private A.myEnum[] tab = {alias_1, alias_2};
}
Using a helper method like
public static myEnum GetEnumName(string str)
{
switch(str)
{
case "alias_1": return myEnum.Value_1;
case "alias_2": return myEnum.Value_2;
default: throw new Exception();
}
}
You just could get all the values and turn them into an array:
myEnum[] tab = Enum.GetValues(typeof(myEnum)).Cast<myEnum>().ToArray();
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.
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
I am using vs 2012. I have a simple string property
string _someString;
public string MyString
{
get
{
return _someString;
}
}
I want this property to hold only certain values. So that when the client uses this property only those certain values can be used.
It sounds like what you really want is an enum:
public enum MyValues //TODO rename all the things
{
SomeValue,
SomeOtherValue,
FinalValue,
}
Then your property can be:
private MyValues value;
public MyValues MyValue
{
get { return value; }
}
If you need to get a string representation of that value just call ToString on the enum value:
string stringValue = value.ToString();
Use an enum as in :
enum MyEnum
{
AllowableValue#1,
AllowableValue#2,
...
}
public MyEnum myEnum { get; set; }
Then populate some UI element with only the values of the enum.
I suppose you want to have some validation on the setter then:
public string MyString
{
get
{
return _someString;
}
set
{
if (value == "a" || value == "b" /* ... */)
_someString = value;
else
throw new InvalidArgumentException("Invalid value!");
}
}
Make sure to set it via the property, not the actual member variable.
i need an enum or something similiar to do something like this:
public enum MyStringEnum {
[StringValue("Foo A")] Foo = "A",
[StringValue("Foo B")] Foo = "B" }
is this possible? my example, i return back a dataset with a value represented as either A,B,C,D,E .. i need a solution to return this as a string representation?
i guess the obvious would be to create an extension method or something which just had a switch statement in and return a string .. any other cleaner solutions?
regards,
dave
Here is something we use for our MVC applications to retrieve a display name for our enums. It uses a custom attribute and an extension method to retrieve the enum display name.
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumDisplayNameAttribute : Attribute
{
public EnumDisplayNameAttribute(string displayName)
{
DisplayName = displayName;
}
public string DisplayName { get; set; }
}
public static string GetDisplayName(this Enum enumType)
{
var displayNameAttribute = enumType.GetType()
.GetField(enumType.ToString())
.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)
.FirstOrDefault() as EnumDisplayNameAttribute;
return displayNameAttribute != null ? displayNameAttribute.DisplayName : Enum.GetName(enumType.GetType(), enumType);
}
Usage on the enum:
public enum Foo
{
[EnumDisplayName("Foo Bar")]
Bar = 0
}
Getting back the display name:
var f = Foo.Bar;
var name = f.GetDisplayName();
Would it be an option not to use enum and use structs instead?
struct FooEnum
{
private int value;
private string name;
private FooEnum(int value, string name)
{
this.name = name;
this.value = value;
}
public static readonly FooEnum A = new FooEnum(0, "Foo A");
public static readonly FooEnum B = new FooEnum(1, "Foo B");
public static readonly FooEnum C = new FooEnum(2, "Foo C");
public static readonly FooEnum D = new FooEnum(3, "Foo D");
public override string ToString()
{
return this.name;
}
//TODO explicit conversion to int etc.
}
You could then use FooEnum like an enum with an own ToString() overload:
FooEnum foo = FooEnum.A;
string s = foo.ToString(); //"Foo A"
If you want to do something like this:
MyStringEnum value = MyStringEnum.A;
string description = value.GetDescription();
// description == "Foo A"
Setup your enum like this:
public enum MyStringEnum
{
[Description("Foo A")]
A,
[Description("Foo B")]
B
}
And use a utility/extension method that reads the attribute:
public static string GetDescription(this MyStringEnum enumerationValue)
{
Type type = enumerationValue.GetType();
string name = enumerationValue.ToString();
//Tries to find a DescriptionAttribute for a potential friendly name for the enum
MemberInfo[] member = type.GetMember(name);
if (member != null && member.Length > 0)
{
object[] attributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
//Pull out the description value
return ((DescriptionAttribute)attributes[0]).Description;
}
}
return name;
}
I've seen this done where I would put
MyStringEnum.Foo.ToString();
In this case it would give "A"
The cleanest solution for this problem is to create a custom attribute that will store the string value you want for the enum constant. I've used that strategy in the past and it worked out fairly well. Here's a blog post detailing the work involved:
Enum With String Values In C# - Stefan Sedich's Blog
Of course this is only necessary if you need some kind of meaningful text. If the name of the enum constant works for you...then you can simply call ToString().