get values(fields) of enum from reflected string representation - c#

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

Related

Get full name of the enum C#

Sample Code:
public enum FruitTypeIs
{
Orange,
Mango,
Banana
}
public void WriteFruitType(FruitTypeIs fruitType)
{
string fruitTypeIs = typeof(FruitTypeIs) + "." + fruitType.ToString(); // -> FruitTypeIs.Mango
Console.WriteLine($"{fruitTypeIs}");
}
In the above sample code, I want to print the received enum value alongwith the enum type. For example, if I receive Mango as the value to the parameter FruitTypeIs fruitType then, I want to print the full value FruitTypeIs.Mango. Since new Fruit types could be added to the enum so, I cannot have a if/switch statement.
As a workaround I can use the statement string fruitTypeIs = typeof(FruitTypeIs) + "." + fruitType.ToString();, which is working fine but is there a better way to do this?
I suggest implementing a generic method
// static - we don't need instance (this) here
// generic - T - suits for any Enum, not necessary FruitTypeIs
public static string FullEnumName<T>(T value) where T : Enum =>
$"{typeof(T).Name}.{Enum.GetName(typeof(T), value)}";
usage:
var value = FruitTypeIs.Mango;
...
Console.Write(FullEnumName(value));
You can implement it as an extension method, e.g.
public static class EnumExtensions {
public static string FullEnumName<T>(this T value) where T : Enum =>
$"{value.GetType().Name}.{Enum.GetName(typeof(T), value)}";
}
and then put it
Console.Write(FruitTypeIs.Mango.FullEnumName());
You can try extension, add an extension for Enum
public static class EnumExtension
{
public static string GetFullType(this Enum e) => $"{e.GetType().Name}.{e}";
}
then you can use this in your code
Console.WriteLine(FruitTypeIs.Banana.GetFullType());

Getting field type default value without instance

I want to get the default value of a type of a field.
I wish to have something like the following code (which of course does not compile):
public class foo
{
public int intf;
public string strf;
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(default(foo.intf)); //Expected default(int)
Console.WriteLine(default(foo.strf)); //Expected default(string)
}
}
Is there any way to do that?
First you need to reflection in order to get the appropriate fields:
var field = typeof(foo).GetField("intf");
Now you can get the return-type of that field:
var type = field.FieldType
Finally you can get the types default-value, e.g. using this approach from Programmatic equivalent of default(Type):
var default = type.IsValueType ? Activator.CreateInstance(type) : null;

Get any enum from ComboBox

I'm programming in WPF(C#). I populate a ComboBox with this function:
public static void PopulateComboBox(ComboBox cmb, Type type)
{
foreach (string name in Enum.GetNames(type))
{
cmb.Items.Add(name);
}
}
Now I need a method like this (as illustrated below) to get any enum as output:
public static enum PopulateComboBox(ComboBox cmb, string nameOfEnum, Type type)
{
}
How can I write such function?
I would look into adding the enum values to the ComboBox directly instead of their names.
Another option would be Enum.Parse(Type enumType, string value).
Finally I found my answer in this page. My answer is:
public static T ToEnum<T>(this string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
For example I call it in this way:
BorderType borderType = ToEnum<BorderType>("Constant");
where BorderType is an enum (from OpenCV);

How can you convert an int to an Enum without knowing the type at design time?

I'm currently refactoring a large codebase and converting it from vb.net to c#. One of the functions does some funky logic around loading columns from a datasource and putting them into properties.
With vb, the creator didn't need to worry about conversions etc. but with c# I need to consider it.
So, given a piece of code like the below, I need to convert an int to the relevant enum type.
public class SomeType
{
public SomeEnum enumValue { get; set; }
public void SetValues()
{
... GetValuesFromDataSource
... Iterates values
enumValue = SetProperty(enumValue, valueFromDataSource);
}
}
protected dynamic SetProperty(object oProperty, object oValue)
{
if (oProperty is Enum)
{
... Convert oValue to the relevant enum type and assign to oProperty
}
}
Just to add some clarity. The references to SetProperty number in the thousands, so I don't want to refactor by hand.
The oValue will come in as an int. There is other logic in the SetProperty method for other types. oProperty could be one of any of the hundreds of enums in the application.
If valueFromDataSource is an object and is just the boxed enum in question, you can use something like the following
if (valueFromDataSource is someEnum)
{
return (someEnum)valueFromDataSource
}
else if (valueFromDataSource is someOtherEnum)
{
return (someOtherEnum)valueFromDataSource
}
However in your original function you're returning back an object, which will box it again, nothing gained
Which leads me to believe your valueFromDataSource is actually an int, therefore, there is no way back, and you would at best have to guess what the enum should be
In a design scenario, your best bet is not store the enum as an int, and just box it
Second would be to leave a hint to the enum type or something
Update
can you convert an int to an Enum without knowing the type at design time?
Unfortunately the answer is no, in VB or C# or any other language, it just cant be done
If your re-factoring code, you must have some wires crossed as the VB creator couldn't do this either
Update to do it more dynamically, using an out parameter for a SetProperty Method
class Program
{
static void Main(string[] args)
{
Entity tt = default(Entity);
Test tester = default(Test);
tester = SetProperty(tester, 5);
tt = SetProperty(tt, "Test7");
Console.WriteLine(tester);
Console.WriteLine(tt);
Console.ReadLine();
}
public static T Cast<T>(T target, object Source)
{
return (T)Source;
}
public static dynamic SetProperty<T>(T target, object source)
{
Type t = typeof(T);
Type sourceType = source.GetType();
if (t.IsEnum)
{
Type enumType = t.GetEnumUnderlyingType();
if (Type.Equals(sourceType, enumType))
{
return (T)Cast(Activator.CreateInstance(enumType), source);
}
if (Type.Equals(sourceType, typeof(string)))
{
Array names = t.GetEnumValues();
foreach (var name in names)
{
if (name.ToString() == source.ToString())
{
return (T)name;
}
}
}
return default(T);
}
return null;
}
public enum Entity
{
Test5,
Test7,
Test8
}
public enum Test : int
{
Test1 = 1,
Test2 = 5,
Test4 = 7
}
}
the output would then be:
Test2
Test7

localizing custom enum property

I have property
public MyEnumType MyType {get; set;}
where MyEnumType is
public enum MyEnumType
{
One = 1,
Two = 2,
Three = 3,
}
is it possible to localize MyType property without modification of MyEnumType
It is not. It is not meant to. That is not output text, that are in program names.
This is not localization (translation of output), what you would do is translate class names in the source code.
Localizing the output you can do with a usual localiazation framework. Depends on output technology.
You can use extension method to create your own ToString() without changing the enumeration itself.
using System;
namespace ConsoleApplication1 {
public enum MyEnumType {
One = 1,
Two = 2,
Three = 3,
}
public static class Extension {
public static string ToLocalizedString(this MyEnumType type) {
// check System.Threading.Thread.CurrentThread.CurrentCulture
// if you need current culture context
switch (type) {
case MyEnumType.One:
return "Ein";
case MyEnumType.Two:
return "Zwei";
case MyEnumType.Three:
return "Drei";
default:
throw new NotImplementedException();
}
}
}
class Program {
static void Main(string[] args) {
var foo = MyEnumType.One;
Console.Out.WriteLine(foo.ToLocalizedString());
}
}
}
If you need to "localize" "ToString" conversion you can go for a static method of a static class
public static class Localization
{
public static string ToCultureString(this MyEnumType type)
{
return ResourceManager.GetString(type.ToString(), Culture);
}
}
! please also take care of:
Culture statement;
Resource files where you have translation for the cooresponded keys
rce files for cultures you need, where you are using keys defined in your enumeration
further you can use the following code:
var asString = MyObj.MyType.ToCultureString();

Categories

Resources