I've a enum class like,
public enum USERTYPE
{
Permanant=1,
Temporary=2,
}
in my business object I just declare this enum as
private List<USERTYPE> userType=new List<USERTYPE>;
and in the get/set method, I tried like
public List<USERTYPE> UserType
{
get
{
return userType;
}
set
{
userType= value;
}
}
here it returns the no of rows as 0, how can I get all the values in the Enum here, can anyone help me here...
You can use this to get all individual enum values:
private List<USERTYPE> userTypes = Enum.GetValues(typeof(USERTYPE)).Cast<USERTYPE>().ToList();
If you do things like this more often, you could create a generic utility method for it:
public static T[] GetEnumValues<T>() where T : struct {
if (!typeof(T).IsEnum) {
throw new ArgumentException("GetValues<T> can only be called for types derived from System.Enum", "T");
}
return (T[])Enum.GetValues(typeof(T));
}
GetValues returns System.Array, but we know it's really a TEnum[] (that is a one-dimensional array indexed from zero) where TEnum is USERTYPE in your case. Therefore use:
var allUsertypeValues = (USERTYPE[])Enum.GetValues(typeof(USERTYPE));
UserTypeCan you please try with that,
UserType = Enum.GetValues(typeof(USERTYPE)).OfType<USERTYPE>().ToList();
If you want to get specific enum value from the list user.UserType then you first need to Add enum value to this list:
var user = new User();
//1 value - PERMANENT
user.UserType.Add(USERTYPE.Permanent);
But if you only need to get all the possible values from an arbitrary enum then you can try Enum.GetValues
//2 values - Permanant and Temporary
var enums = Enum.GetValues(typeof(USERTYPE));
What you have is basically List of enum. Not individual items inside that enum.
To get list of enum values you can do
string[] str = Enum.GetNames(typeof(USERTYPE));
To use in get/set return string[] instead of List<>
public string[] UserType
{
get
{
return Enum.GetNames(typeof(USERTYPE));
}
}
I think set will not work here because you cannot add values in enum at runtime.
Related
Is there a way how to return full enum by property? Here is example of what I want to do:
// MyEnums.cs
public enum Languages
{
cs = 0,
pl = 1,
en = 2,
de = 3,
}
// General.cs
public static MyEnums.Languages Languages
{
get
{
return MyEnums.Languages;
}
}
enum is a type, i guess you actually want to get all enum-values. You could use this wrapper:
public static class EnumWrapper<T> where T : struct
{
public static T[] Values
{
get
{
Type ofT = typeof(T);
if (!ofT.IsEnum) throw new ArgumentException("Must be enum type");
return Enum.GetValues(ofT).Cast<T>().ToArray();
}
}
}
// ...
Languages[] languages = EnumWrapper<Languages>.Values;
If you want to return all available values defined in the enum, you can use
Enum.GetValues(typeof(MyEnums.Languages));
and modify your method so it returns a MyEnums.Languages[] (or a List<MyEnums.Languages>, which is always easier to manage for calling code)
To get all values in the enum, use Enum.GetValues. You might also want to cast it back to the correct type:
Languages[] languages = Enum.GetValues(typeof(Languages)).Cast<Languages>().ToArray();
// languages is an array containing { Languages.cs, Languages.pl, Languages.en, Languages.de }
I have a flaggable enum from a database that I want to convert to an enum array of a 3rd party.
For that, I'm using the following code:
private TheirEnum[] GetTheirEnums(MyEnum? ourEnums)
{
List<TheirEnum> result = new List<TheirEnum>();
if (ourEnums != null)
{
if (ourEnums.Value.HasFlag(MyEnum.Geothermal))
{
result.Add(TheirEnum.GEOTHERMAL);
}
if (ourEnums.Value.HasFlag(MyEnum.SolarHeating))
{
result.Add(TheirEnum.SOLAR_HEATING);
}
}
else
{
result.Add(TheirEnum.NO_INFORMATION);
}
return result.ToArray();
}
However, as there are more than 50 entries in that enum list, I assume this would get very messy and ugly. Is there a better way to do this?
A simple solution would be to create OurEnum based on TheirEnum, then a simple cast would do the trick.
here is an example:
[Flags]
public enum TheirEnum
{
GEOTHERMAL=1,
SOLAR_HEATING=2,
NO_INFORMATION=4
}
[Flags]
public enum OurEnum
{
Geothermal=TheirEnum.GEOTHERMAL,
SolarHeating=TheirEnum.SOLAR_HEATING,
NoInformation=TheirEnum.NO_INFORMATION
}
or even you can just use the values:
[Flags]
public enum OurEnum
{
Geothermal=1,
SolarHeating=2,
NoInformation=4
}
then a simple cast would convert it:
var ourValue = OurEnum.Geothermal | OurEnum.NoInformation;
var theirValue = (TheirEnum) ourValue;
at last we can simply create an array based on flagged enums in theirValue :
var values=Enum.GetValues(typeof(TheirEnum));
var array= (from TheirEnum v in values where theirValue.HasFlag(v) select v).ToArray();
I have enum:
enum MyEnum{
aaaVal1,
aaaVal2,
aaaVal3,
}
I need to have abbreviated version of 'MyEnum' which maps every item from 'MyEnum' to different values. My current approach is method which simply translates every item:
string translate(MyEnum myEnum)
{
string result = "";
switch ((int)myEnum)
{
0: result = "abc";
1: result = "dft";
default: result = "fsdfds"
}
return result;
}
the problem with this approach is that every time programmer changes MyEnum he should also change translate method.
This is not a good way of programming.
So..
Is there any more elegant solution for this problem?
Thank you :-)
Four options:
Decorate your enum values with attributes, e.g.
enum MyEnum
{
[Description("abc")]
AaaVal1,
[Description("dft")]
AaaVal2,
AaaVal3,
}
Then you can create a mapping (like the dictionary solution below) via reflection.
Keep the switch statement but switch on the enum value instead of a number for better readability:
switch (myEnum)
{
case MyEnum.AaaVal1: return "abc";
case MyEnum.AaaVal2: return "dft";
default: return "fsdfds";
}
Create a Dictionary<MyEnum, string>:
private static Dictionary<MyEnum, string> EnumDescriptions =
new Dictionary<MyEnum, string>
{
{ MyEnum.AaaVal1, "abc" },
{ MyEnum.AaaVal2, "dft" },
};
You'd need to handle the defaulting in the method, of course.
Use a resource file, with an entry for each string representation. This would be better if you're really trying to translate in a way that might need different translations for different cultures.
Considering that the use of descriptors on enums is quite common, here it's a good-enough class to do it:
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
class EnumDescriptor : Attribute
{
public readonly string Description;
public EnumDescriptor(string description)
{
this.Description = description;
}
public static string GetFromValue<T>(T value) where T : struct
{
var type = typeof(T);
var memInfo = type.GetField(value.ToString());
var attributes = memInfo.GetCustomAttributes(typeof(EnumDescriptor), false);
if (attributes.Length == 0)
{
return null;
}
return ((EnumDescriptor)attributes[0]).Description;
}
}
enum MyEnum
{
[EnumDescriptor("Hello")]
aaaVal1,
aaaVal2,
aaaVal3,
}
string translate(MyEnum myEnum)
{
// The ?? operator returns the left value unless the lv is null,
// if it's null it returns the right value.
string result = EnumDescriptor.GetFromValue(myEnum) ?? "fsdfds";
return result;
}
I'm finding what you're trying to do a bit weird.
If you're making translations, then you should create a RESX file and create ACTUAL translations.
But to answer your question, I guess you could create another enum with the same amount of fields and same numbering (if you're using anything other than the default) and have that act as the abbreviated names. Connecting one to the other should be straightforward:
string GetAbbreviation(Enum1 enum1)
{
return ((Enum2)((int)enum1)).ToString();
}
Attributes will be nice solution for this case. You can specify translations for enumeration members via declarative way:
public class TranslateAttribute
{
public string Translation { get; private set; }
public TranslateAttribute(string translation)
{
Translation = translation;
}
}
enum MyEnum
{
[Translate("abc")]
aaaVal1,
[Translate("dft")]
aaaVal2,
[Translate("fsdfds")]
aaaVal3
}
After this you should write common method for obtaining translations. It should check attribute with translation (via reflection) and return translation if it was specified and default value in other cases.
As title says, from this enum:
public enum DeeMacsEnum
{
Value1,
Value2,
Value3
}
I would like a List<String>. First element will have "Value1", second will be "Value2" etc.
However, I would like to keep this method generic enough for it to iterate through any type of enum
What I've Tried:
Array values = Enum.GetValues(typeof(DeeMacsEnum));
^ This works fine. But not generic. In an attempt to make it reusable I changed it to this:
var type = enumObject.GetType();
Array values = Enum.GetValues(typeof(type));
Doesn't work (doesn't even compile), understandably.
You actually have type, no need to use typeof anymore
var type = enumObject.GetType();
Array values = Enum.GetValues(type);
Try:
var names = Enum.GetNames(typeof(DeeMacsEnum));
You can use this:
string[] s = Enum.GetNames(typeof(YourEnumType));
why not try this
public IEnumerable<string> getEnumValues<T>() where T: struct,IConvertible
{
var type = typeof(T);
if (type.IsEnum)
{
return Enum.GetNames(type);
}
else
{
throw new ArgumentException("Type parameter specified is not an enum type.");
}
}
I have an enum and i want to "hide" one of its values (as i add it for future support).
The code is written in C#.
public enum MyEnum
{
ValueA = 0,
ValueB = 1,
Reserved
}
I don't want to allow peoples who use this code to use this values (MyEnum.Reserved).
Any idea?
TIA
You could use the 'Obsolete' attribute - semantically incorrect, but it will do what you want:
public enum MyEnum
{
ValueA = 0,
ValueB = 1,
[Obsolete("Do not use this", true)]
Reserved
}
Anyone who tries to compile using the Foo.Reserved item will get an error
If you don't want to show it, then don't include it:
public enum MyEnum
{
ValueA = 0,
ValueB = 1,
}
Note that a user of this enum can still assign any integer value to a variable declared as MyEnum:
MyEnum e = (MyEnum)2; // works!
This means that a method that accepts an enum should always validate this input before using it:
void DoIt(MyEnum e)
{
if (e != MyEnum.ValueA && e != MyEnum.ValueB)
{
throw new ArgumentException();
}
// ...
}
So, just add your value later, when you need it, and modify your methods to accept it then.
This is not possible in C#. All enum values are accessible if the Enum itself is accessible.
The only way you could simulate accomplishing this is by using a less accessible static field that used an integer value not already used in the Enum.
public enum MyEnum {
ValueA = 0;
ValueB = 1;
}
internal static class MyEnumEx {
internal static MyEnum Reserved = (MyEnum)42;
}
I'm curious though as to why you would want to do this. No matter what you do users can still provide the Reserved value. All that needs to be done is to cast an int of the appropriate value to the MyEnum type.
// Code that shouldn't access Reserve
MyEnum reserved = (MyEnum)42; // Woot!
if you want to hide from intellisense or PropertyGrid enumerated members, you can apply:
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
and
[System.ComponentModel.Browsable(false)]
Example:
public enum MyEnum
{
A,
B,
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
C
}
C is not visible
You can achieve something like this by using your own custom type instead of enum:
// This type works pretty much the same way an enum works;
// each specific value can be cast to/from an int, and each has
// a specific name that is returned on calling ToString().
public sealed class MyEnum
{
private readonly int _value;
private readonly string _name;
// private constructor -- ensure that the static members you define below
// are the only MyEnum instances accessible from any outside code
private MyEnum(int value, string name)
{
_value = value;
_name = name;
}
// no need to override Equals or GetHashCode, believe it or not --
// one instance per value means we can use reference equality and
// that should be just fine
public override string ToString()
{
return _name;
}
// provide direct access only to these members
public static readonly MyEnum ValueA = new MyEnum(0, "ValueA");
public static readonly MyEnum ValueB = new MyEnum(1, "ValueB");
// this member is only available to you within the current assembly
internal static readonly MyEnum Reserved = new MyEnum(-1, "Reserved");
}
You could even further emulate the behavior of enum values by, for example, overloading the explicit operators to convert to/from MyEnum objects to int values (took JaredPar's suggestion to use this rather than implicit):
public static explicit operator MyEnum(int value)
{
switch (value)
{
case 0:
return ValueA;
case 1:
return ValueB;
default:
throw new InvalidCastException();
}
}
public static explicit operator int(MyEnum value)
{
return value._value;
}
You can't hide it, but you can add a comment that this value doesn't have any effect at this moment. Otherwise just remove it and add it if you add the support, this shouldn't break any other code dependent on it, as long as the original values don't change.
Are you using the "hidden" value internally? If not:
public enum MyEnum
{
ValueA = 0,
ValueB = 1,
//TODO: Reserved
}
You gain nothing by defining an unused variable.
one way you can do this set the value of this variable null.
so when ever its called from enum it'll b null. in short user can't access its value.
public enum MyEnum
{
ValueA = 0,
ValueB = 1,
Reserved.None
}
I had a similar problem with enum Flags, but the solution I used should work without the Flags attribute.
You can create two enum types, one for the reserved values and the other for the publicly usable values. You can use HasFlag with the reserved type without casting, but assignment requires casting.
[Flags]
public enum MyEnumReserved {
Income = 1,
Expense = 2,
Discretionary = 4,
Critical = 8
}
[Flags]
public enum MyEnum {
Income = MyEnumReserved.Income,
DiscretionaryExpense = MyEnumReserved.Expense | MyEnumReserved.Discretionary,
CriticalExpense = MyEnumReserved.Expense | MyEnumReserved.Critical
}
bool IsIncome(MyEnum val) => val.HasFlag(MyEnumReserved.Income);
...
MyEnum foo = (MyEnum)MyEnumReserved.Expense | (MyEnum)MyEnumReserved.Discretionary;