I have the below scenario
public class TestData
{
public TestEnum EnumTestData{get;set;}
}
public Enum TestEnum
{
Test1,Test2,Test3
}
I have another class which traverse through my TestData class for all properties. Depending on the property type it will generate random data for it. Now when my propertyType is Enum type, How can I know which type of enum it is and how to get either Test1, Test2 or Test3 as my output?
You can get a list of all properties using the Type.GetProperties method:
var targetType = typeof(TestData);
var properties = targetType.GetProperties();
Then check whether it's an Enum type by checking the PropertyInfo.PropertyType and Type.IsEnum properties:
foreach(var prop in properties)
{
if (prop.PropertyType.IsEnum)
{
...
}
}
Finally get a random value using the Enum.GetValues method:
var random = new Random();
...
var values = Enum.GetValues(prop.PropertyType);
var randomValue = ((IList)values)[random.Next(values.Length)];
You can just .ToString() the EnumTestData property, like this:
var test = new TestData();
test.EnumTestData = TestEnum.Test1;
var dummy = test.EnumTestData.ToString();
Note: dummy will be "Test1".
Not entirely sure what you're asking, but this is how you would compare and get the string value of an enum:
var td = new TestData();
// compare
if (td.EnumTestData == TestEnum.Test1)
{
// Will output "Test1"
Console.WriteLine(td.EnumTestData.ToString());
}
Also, I'm sure it's just a typo but it's enum not Enum:
public enum TestEnum
{
Test1,Test2,Test3
}
Related
below is the Enum from which i need to populate object list
public enum Scope
{
[Description("Organization")]
Organization = 100,
[Description("Organization#Unit")]
Organization_Unit = 200,
[Description("Organization#Unit#User")]
Organization_Unit_User = 300
}
I have to create object list from this Enum
Object skeleton will be like below
public class ScopeKVP {
public string key {get;set;}
public int value {get;set;}
}
At the end I need below list of object from enum in which description of each enum should be save in key property of object and value of enum should be saved in value property of object like below
var scopeKvp = new List<ScopeKVP> {
new ScopeKVP {key= 100,value="Organization"},
new ScopeKVP {key= 200,value="Organization#Unit"},
new ScopeKVP {key= 300,value="Organization#Unit#User"}
}
This is what you need to do:
Use reflection to get the information about the enum, its fields
Loop the fields
Take their value with GetValue method
Take the attribute Description's description, which is what you passed to
its constructor
Create the object of type ScopeKVP and add it to
the result list
Code:
Type enumType = typeof(Scope);
FieldInfo[] fields = enumType.GetFields();
List<ScopeKVP> scopeKvp = new List<ScopeKVP>();
foreach (FieldInfo field in fields)
{
if (field.IsLiteral)
{
DescriptionAttribute descAttr = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
ScopeKVP item = new ScopeKVP()
{
key = descAttr.Description,
value = (int)field.GetValue(null)
};
scopeKvp.Add(item);
}
}
// scopeKvp is what you need
P.S. like the comments above state, you have some mismatch for key which is string and you expect integer. I guess it is a typo.
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 a class with custom enum:
public enum Capabilities{
PowerSave= 1,
PnP =2,
Shared=3, }
My class
public class Device
{
....
public Capabilities[] DeviceCapabilities
{
get { // logic goes here}
}
Is there a way using reflection to get the value of this field during runtime?
I tried the following but got null reference exception
PropertyInfo[] prs = srcObj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in prs)
{
if (property.PropertyType.IsArray)
{
Array a = (Array)property.GetValue(srcObj, null);
}
}
EDIT: Thanks for your answers, what I really need is a way to get the values dynamically without the need to specify the enum type.
Something like:
string enumType = "enumtype"
var property = typeof(Device).GetProperty(enumType);
Is that possible?
The following should do what you desire.
var property = typeof(Device).GetProperty("DeviceCapabilities");
var deviceCapabilities = (Capabilities[])property.GetValue(device);
Note that the method Object PropertyInfo.GetValue(Object) is new in .NET 4.5. In previous versions you have to add an additional argument for the indices.
var deviceCapabilities = (Capabilities[])property.GetValue(device, null);
This should work:
var source = new Device();
var property = source.GetType().GetProperty("DeviceCapabilities");
var caps = (Array)property.GetValue(source, null);
foreach (var cap in caps)
Console.WriteLine(cap);
If you want to enumerate all the possible values of an Enum and return as an array then try this helper function:
public class EnumHelper {
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
Then you can simply call:
Capabilities[] array = EnumHelper.GetValues<Capabilities>();
If that isn't what you are after then I'm not sure what you mean.
You can try this
foreach (PropertyInfo property in prs)
{
string[] enumValues = Enum.GetNames(property.PropertyType);
}
Hope it helps.
If I have the following:
public enum TYPE
{
One = 1,
Two = 2,
Three = 3
}
When I do:
var a = TYPE.One;
I would like it to populate the variable a with a string in the format "01". In other words two digits with a leading zero.
Is it possible to do this by assigning some method to the SomeEnum? I realized I could use TYPE.One.ToString("00")but I would like to have it self-contained in the enum and something very simple to use.
You can add a string to each enum element using the description attribute.
e.g.
public Enum MyEnum
{
[Description("Value A Description")]
ValueA,
[Description[("Value B Description")]
ValueB
}
To retrieve the description value, use an extender class
public static class MyEnumExtender
{
public static string Description(this Enum Value)
{
FieldInfo FI = Value.GetType().GetField(Value.ToString());
IEnumerable<DescriptionAttribute> Attributes = FI.GetCustomAttributes(typeof(DescriptionAttribute), false).Cast<DescriptionAttribute>();
return (Attributes.Any()) ? Attributes.First().Description : Value.ToString();
}
}
....
MyEnum EnumVar = MyEnum.ValueA;
string Description = EnumVar.Description();
can do something like this :
public static class Ext {
public static string ToMyString(this Enumer en ) {
return ((int)en).ToString("00");
}
}
and after use this like:
public enum TYPE { One = 1, Two = 2, Three = 3 }
Type t = TYPE.One;
string s = t.ToMyString();
Yes, conceptually it's the same as like declaring a string , but it's hidden inside extension method.
Other solution is: to simply avoid, at this point, using enums in that way.
Don't use enums for that, but something like a Dictionary or Hash. Enums are there when there is a limited set of possibilities and you do not want or need a value. How it is stored is irrelevant.
I have a string representation of an enum.
string val = "namespace_name.enum_name";
I can use this to get type of enum.
Type myType = Type.GetType(val);
Now I see myType.Name = actual_enum_name and other informations, good.
I have tried to obtain the actual enum values using this information and not successful.
I have tried using Enum.Getvalues, however I got stuck in converting the myType, which is System.Type to EnumType, which is what Enum.Getvalues require(?).
I have tried to actually create an Enum object based on the information obtained and got stuck.
How can I get actual fields (list of members) of that enum from here?
That should work as is, no conversion required. Enum.GetValues() takes a Type. The code below works.
namespace enumtest
{
public enum Mine
{
data1,
data2
}
class Program
{
static void Main(string[] args)
{
Type myenum = Type.GetType("enumtest.Mine");
foreach (var curr in Enum.GetValues(myenum))
{
Console.WriteLine(curr.ToString());
}
}
}
}
This allows you to construct instances of an enum value like this:
namespace enumtest
{
public enum Mine
{
data1,
data2
}
class Program
{
static void Main(string[] args)
{
Type myenum = Type.GetType("enumtest.Mine");
// Let's create an instance now
var values = Enum.GetValues(myenum);
var firstValue = values.GetValue(0);
Mine enumInstance = (Mine)Enum.Parse(myenum, firstValue.ToString());
Console.WriteLine("I have an instance of the enum! {0}", enumInstance);
}
}
}
Suppose i have an Enum ContactNumberType then to get values use
string[] names = Enum.GetValues(typeof(ContactNumberType));
because GetValues() method returns an array