How to set string in Enum C#? - c#

I want to create string ENUM in c#.
Basically i wan't to set form name in Enum. When i open form in main page that time i want to switch case for form name and open that particular form.
I know ENUM allows only integer but i want to set it to string.
Any Idea?

Enum cannot be string but you can attach attribute and than you can read the value of enum as below....................
public enum States
{
[Description("New Mexico")]
NewMexico,
[Description("New York")]
NewYork,
[Description("South Carolina")]
SouthCarolina
}
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
here is good article if you want to go through it : Associating Strings with enums in C#

As everyone mentioned, enums can't be strings (or anything else except integers) in C#. I'm guessing you come from Java? It would be nice if .NET had this feature, where enums can be any type.
The way I usually circumvent this is using a static class:
public static class MyValues
{
public static string ValueA { get { return "A"; } }
public static string ValueB { get { return "B"; } }
}
With this technique, you can also use any type. You can call it just like you would use enums:
if (value == MyValues.ValueA)
{
// do something
}

Do this:
private IddFilterCompareToCurrent myEnum =
(IddFilterCompareToCurrent )Enum.Parse(typeof(IddFilterCompareToCurrent[1]),domainUpDown1.SelectedItem.ToString());
[Enum.parse] returns an Object, so you need to cast it.

Im not sure if I understood you corectly but I think you are looking for this?
public enum State { State1, State2, State3 };
public static State CurrentState = State.State1;
if(CurrentState == State.State1)
{
//do something
}

I don't think that enums are the best solution for your problem. As others have already mentionde, the values of an enum can only be integer values.
You could simply use a Dictionary to store the forms along with their name like:
Dictionary<string, Form> formDict = new Dictionary<string, Form>();
private void addFormToDict(Form form) {
formDict[form.Name] = form;
}
// ...
addFormToDict(new MyFirstForm());
addFormToDict(new MySecondForm());
// ... add all forms you want to display to the dictionary
if (formDict.ContainsKey(formName))
formDict[formName].Show();
else
MessageBox.Show(String.Format("Couldn't find form '{0}'", formName));

Either make the names of the Enum members exactly what you want and use .ToString(),
Write a function like this ...
string MyEnumString(MyEnum value)
{
const string MyEnumValue1String = "any string I like 1";
const string MyEnumValue2String = "any string I like 2";
...
switch (value)
{
case MyEnum.Value1:
return MyEnumValue1String;
case MyEnum.Value2:
return MyEnumValue2String;
...
}
}
Or use some dictionary or hash set of values and strings instead.

string enums don't exist in C#. See this related question.
Why don't you use an int (default type for enums) instead of a string?

Related

Enforcing static class constants as a data type

I have a static class with constants. I am looking for options to create a method which takes a dictionary as an argument and enforcing the key to be one of the constants from the static class.Here is my static class with constants.
Here is what I am trying to do
And here is what I am trying to enforce
From the sound of it, an Enum would be more suited to what you're trying to do.
public enum MyConstants
{
FirstName,
LastName,
Title
}
public void CreateMe(Dictionary<MyConstants, string> propertyBag)
{
...
}
UPDATED
You could combine this with attributes to associate each enum with a specific string like so:
public enum PropertyNames
{
[Description("first_name")]
FirstName,
[Description("last_name")]
LastName,
[Description("title")]
Title
}
The value of each description attribute associated with each enum value could easily be grabbed via an extension method, like so:
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fieldInfo.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
Then in your "CreateMe"-method you can get the description and value of each dictionary entry by doing something similar to this:
void CreateMe(Dictionary<PropertyNames, string> propertyBag)
{
foreach (var propertyPair in propertyBag)
{
string propertyName = propertyPair.Key.GetDescription();
string propertyValue = propertyPair.Value;
}
}
Even though this has been already answered, there is another approach, like so:
public class MyOwnEnum
{
public string Value { get; private set; }
private MyOwnEnum(string value)
{
Value = value;
}
public static readonly MyOwnEnum FirstName = new MyOwnEnum("Firstname");
public static readonly MyOwnEnum LastName = new MyOwnEnum("LastName");
}
It behaves same way like Enum and can be used in your code with same syntax. I cannot give credit to whoever came up with it, but I believe I came upon it when searching for Enums with multiple values.
With strings you can't enforce fact that keys come from limited set of vialues compile time.
Use enum or custom class (possibly with implicit conversion to string) instead.

Can I access a class variable with another variable?

i want to do a class constructor that takes a dicionary as parameter and initialize all the class variables that are listed as key in the dictionary, after of course a type conversion:
public class User
{
public int id;
public string username;
public string password;
public string email;
public int mana_fire;
public int mana_water;
public int mana_earth;
public int mana_life;
public int mana_death;
public User ()
{
}
public User(Dictionary<string,string> dataArray){
FieldInfo[] classVariablesInfoList = typeof(User).GetFields();
for(int i = 0; i < classVariablesInfoList.Length; i++)
{
if(dataArray.ContainsKey(classVariablesInfoList[i].Name)){
//missing code here :)
//need something like classVariable= dataArray["classVariablesInfolist[i].name"]; ?
}
}
}
}
but i can't find out how to do this!
Can you please help? :)
You can use the SetValue frunction from reflection:
FieldInfo f = classVariablesInfoList[i];
if (f.ReflectedType == typeof(int))
{
f.SetValue(this, Convert.ToInt32(dataArray[f.Name]));
}
else
{
f.SetValue(this, dataArray[classVariablesInfoList[i].Name]);
}
But it is a really uncommon way to do this with a dictionary. You should considder accessing the fields directly or add parameters to the constructor for any field. And fields should never be public - use properties instead.
The following will work if Convert.ChangeType() is able to handle the conversion. There are a lot of problems waiting to occur, for example handling numbers or dates where the string representation depends on the locale. I would really suggest to use usual typed constructor parameters or standard (de)serialization mechanism if possible. Or at least use a dictionary containing objects instead of strings to get rid of the conversion, again if possible.
public User(Dictionary<String, String> data)
{
var fields = typeof(User).GetFields();
foreach (field in fields)
{
if (data.ContainsKey(field.Name))
{
var value = Convert.ChangeType(data[field.Name], field.MemberType);
field.SetValue(this, value);
}
}
}
I would like to separate your problem into two parts.
1. Applying conversion
The FieldInfo type present a FieldType property that is the actual type of the field, using this Type we can use the non-generic ChangeType method of System.Convert, this method will be able convert some types to others. Luckily it support String to Int.
Usage:
Convert.ChangeType(OLD_VALUE, TARGET_TYPE);
2. Setting the field
The field info class has a SetValue method (FieldInfo.SetValue), it has two parameters, the first one is the current (ie. this) instance (or the instance you wish to change). the second is the new value you wish to set.
Putting it all together
[...]
var fieldInfo = classVariablesInfoList[i];
var name = fieldInfo.Name;
var targetType = fieldInfo.Type;
var value = Convert.ChangeType(dataArray[name], targetType);
classVariablesInfoList[i].SetValue(this, value);

Change enum display

How can i have a c# enum that if i chose to string it returns a different string, like in java it can be done by
public enum sample{
some, other, things;
public string toString(){
switch(this){
case some: return "you choose some";
default: break;
}
}
}
Console.writeln(sample.some) will output:
you choose some
i just want my enums to return a different string when i try to call them.
To my knowledge this is not possible. However, you can write an extension method that gets some other string:
public static class EnumExtensions
{
public static string ToSampleString(this SampleEnum enum)
{
switch(enum)
{
case SampleEnum.Value1 : return "Foo";
etc.
}
}
}
Now, just call this new ToSampleString on instances of SampleEnum:
mySampleEnum.ToSampleString();
If you are unfamiliar with extension methods in C#, read more here.
Another option is to use an Description attribute above each enum value, as described here.
I would do it decoratively by creating an attribute e.g. Description and decorating the enum values with it.
e.g.
public enum Rate
{
[Description("Flat Rate")]
Flat,
[Description("Time and Materials")]
TM
}
Then use GetCustomAttributes to read/display the values. http://msdn.microsoft.com/en-us/library/system.attribute.getcustomattributes.aspx
#CodeCamper Sorry about the late response but here is some example code to read the DescriptionAttribute:
Extension method:
public static class EnumExtensions
{
public static string Description<T>(this T t)
{
var descriptionAttribute = (DescriptionAttribute) typeof (T).GetMember(t.ToString())
.First().GetCustomAttribute(typeof (DescriptionAttribute));
return descriptionAttribute == null ? "" : descriptionAttribute.Description;
}
}
Usage:
Rate currentRate = Rate.TM;
Console.WriteLine(currentRate.Description());
You want a dictionary. An enumerator enumerates (gives a number) for its values. You want a string value to be returned when you provide a string key. Try something like:
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("some", "you choose some");
dictionary.Add("other", "you choose other");
dictionary.Add("things", "you choose things");
Then this code:
string value = dictionary["some"];
Console.writeln(value);
will return "you choose some"
If you just want to get Enum as string you can use this method:
Enum.GetName(typeof(sample), value);
This method will return the name of Enum instead of int.

Creating enums having Key Value as string

I know following syntax is possible with enum, and one can get value by parsing it in int or char.
public enum Animal { Tiger=1, Lion=2 }
public enum Animal { Tiger='T', Lion='L' }
Although following syntax is also right
public enum Anumal { Tiger="TIG", Lion="LIO"}
How do I get the value in this case? If I convert it using ToString(), I get the KEY not the VALUE.
If you really insist on using enum to do this, you can do it by having a Description attribute and getting them via Reflection.
public enum Animal
{
[Description("TIG")]
Tiger,
[Description("LIO")]
Lion
}
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
Then get the value by string description = GetEnumDescription(Animal.Tiger);
Or by using extension methods:
public static class EnumExtensions
{
public static string GetEnumDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
Then use it by string description = Animal.Lion.GetEnumDescription();
You can't use strings in enums. Use one or multiple dictionaries istead:
Dictionary<Animal, String> Deers = new Dictionary<Animal, String>
{
{ Animal.Tiger, "TIG" },
{ ... }
};
Now you can get the string by using:
Console.WriteLine(Deers[Animal.Tiger]);
If your deer numbers are in line ( No gaps and starting at zero: 0, 1, 2, 3, ....) you could also use a array:
String[] Deers = new String[] { "TIG", "LIO" };
And use it this way:
Console.WriteLine(Deers[(int)Animal.Tiger]);
Extension method
If you prefer not writing every time the code above every single time you could also use extension methods:
public static String AsString(this Animal value) => Deers.TryGetValue(value, out Animal result) ? result : null;
or if you use a simple array
public static String AsString(this Animal value)
{
Int32 index = (Int32)value;
return (index > -1 && index < Deers.Length) ? Deers[index] : null;
}
and use it this way:
Animal myAnimal = Animal.Tiger;
Console.WriteLine(myAnimal.AsString());
Other possibilities
Its also possible to do the hole stuff by using reflection, but this depends how your performance should be ( see aiapatag's answer ).
That is not possible, the value of the enum must be mapped to a numeric data type. (char is actually a number wich is wirtten as a letter)
However one solution could be to have aliases with same value such as:
public enum Anumal { Tiger=1, TIG = 1, Lion= 2, LIO=2}
Hope this helps!
This isn't possible with Enums. http://msdn.microsoft.com/de-de/library/sbbt4032(v=vs.80).aspx
You can only parse INT Values back.
I would recommend static members:
public class Animal
{
public static string Tiger="TIG";
public static string Lion="LIO";
}
I think it's easier to handle.
As DonBoitnott said in comment, that should produce compile error. I just tried and it does produce. Enum is int type actually, and since char type is subset of int you can assign 'T' to enum but you cannot assign string to enum.
If you want to print 'T' of some number instead of Tiger, you just need to cast enum to that type.
((char)Animal.Tiger).ToString()
or
((int)Animal.Tiger).ToString()
Possible alternative solution:
public enum SexCode : byte { Male = 77, Female = 70 } // ascii values
after that, you can apply this trategy in your class
class contact {
public SexCode sex {get; set;} // selected from enum
public string sexST { get {((char)sex).ToString();}} // used in code
}

Converting a string to a custom enum

I'm trying to set a custom enum property on a custom object by looking at a string value that is held in another object, but I keep getting the error "cannot reference a type through an expression."
so far I've tried
rec.Course = (CourseEnum)Enum.Parse(typeof(CourseEnum), rr.course);
where rec.Course wants a member of the CourseEnum Enumeration, and rr.course is a string.
I also tried to do a switch statement where the value of rr.course is checked (there are only certain values it can be) but get the same result
the enum is defined as follows:
public enum CourseEnum
{
[StringValue("Starters")]
Starters,
[StringValue("Main Course")]
MainCourse,
[StringValue("Desserts")]
Desserts
};
public class StringValue : System.Attribute
{
private string _value;
public StringValue(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
public static class StringEnum
{
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
//Check first in our cached results...
//Look for our 'StringValueAttribute'
//in the field's custom attributes
FieldInfo fi = type.GetRuntimeField(value.ToString());
StringValue[] attrs =
fi.GetCustomAttributes(typeof(StringValue),
false) as StringValue[];
if (attrs.Length > 0)
{
output = attrs[0].Value;
}
return output;
}
}
I can see in your code that your using Enum.Parse with CourseEnum and it should be recipeCourse I presume.
I can't spot any place in your sample code where4 CourseEnum is defined.
A #Hans Kesting said, the answer was here: Why can not reference a type through an expression?
The problem was using a field that has an enum type with the enum type itself.

Categories