Enum Extension Method is not showing - c#

I'm trying to add new/extension method for Enum but the extension method is not showing on intellisense method list. Please help here's my code.
Extension:
public static class EnumExtensions
{
public static string GetDescriptionAttr(this Enum value,string key)
{
var type = value.GetType();
var memInfo = type.GetMember(key);
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
false);
var description = ((DescriptionAttribute)attributes[0]).Description;
return description;
}
}
Trying to call the result from other class (both caller and extension are in the same project)

Extension methods can be applied on instances only
public static class EnumExtensions {
// This extension method requires "value" argument
// that should be an instance of Enum class
public static string GetDescriptionAttr(this Enum value, string key) {
...
}
}
...
public enum MyEnum {
One,
Two,
Three
}
Enum myEnum = MyEnum.One;
// You can call extension method on instance (myEnum) only
myEnum.GetDescriptionAttr("One");

You should use extension method for an instance of your enum.
I have this code and it works properly:
public static string GetDescription(this Enum value)
{
var attributes =
(DescriptionAttribute[])value.GetType().GetField(value.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
And using of this method shows here:
MyEnum myE = MyEnum.OneOfItemsOfEnum;
string description = myE.GetDescription();

I have this variant
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
namespace Web.Extensions
{
public static class EnumExtension
{
public static string GetDisplayName(this Enum enumValue)
{
var displayName = enumValue.GetType()?
.GetMember(enumValue.ToString())
.FirstOrDefault()?
.GetCustomAttribute<DisplayAttribute>()?
.Name;
return displayName ?? enumValue.ToString();
}
}
}
enum definition
public enum SomeEnum
{
One= 1,
[Display(Name = "Second")]
Two= 2,
Three= 3
}
and in view (extension called directly).
display name from enum
#Web.Extensions.EnumExtension.GetDisplayName(Domain.Enums.SomeEnum.Two)
show display name from enum id
#Web.Extensions.EnumExtension.GetDisplayName((Domain.Enums.SomeEnum)2)
show display name from enum id without display attribute
#Web.Extensions.EnumExtension.GetDisplayName((Domain.Enums.SomeEnum)3)
outputs
Second
Second
Three
or more simply
#using Web.Extensions
#using Domain.Enums
#SomeEnum.Two.GetDisplayName()
#(((SomeEnum)2).GetDisplayName())

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.

Parse StringValueAttribute to return Enum

I currently have a windows phone 8.1 runtime project with enums that use a string value attribute. I want to be able to get an enum value by using the string value attribute, for example use "world" to get the enum value of summer. I am using Windows phone 8.1 runtime so most methods that I have found do not work.
Thanks in advance.
public enum test
{
[StringValue("hello")]
school,
[StringValue("world")]
summer,
[StringValue("fall")]
car
}
public class StringValueAttribute : Attribute
{
private string _value;
public StringValueAttribute(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
To get to your Attributes you will need to use a method/extension. Folowing this question and answer you can make such a thing:
public class StringValueAttribute : Attribute
{
private string _value;
public StringValueAttribute(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
public static string GetStringValue(Enum value)
{
Type type = value.GetType();
FieldInfo fi = type.GetRuntimeField(value.ToString());
return (fi.GetCustomAttributes(typeof(StringValueAttribute), false).FirstOrDefault() as StringValueAttribute).Value;
}
}
Then using this line of code:
string stringTest = StringValueAttribute.GetStringValue(test.summer);
will give a result of "world". (Opposite what you wanted, but hopefuly will give you an idea how to deal with the problem).
Depending on what you want to achieve, you can probably use different methods linke: using Dictionary, struct, properties and probably different ways.
As for parsing Enum values you can achieve it like this:
test testValue = test.summer;
string testString = testValue.ToString();
test EnumValue = (test)Enum.Parse(typeof(test), testString);
EDIT
If you want to get enum from attribute, then this method (probably should be improved) should do the job:
public static T GetFromAttribute<T>(string attributeName)
{
Type type = typeof(T);
return (T)Enum.Parse(typeof(T), type.GetRuntimeFields().FirstOrDefault(
x => (x.CustomAttributes.Count() > 0 && (x.CustomAttributes.FirstOrDefault().ConstructorArguments.FirstOrDefault().Value as string).Equals(attributeName))).Name);
}
Usage:
test EnumTest = StringValueAttribute.GetFromAttribute<test>("world");

How to set two values for same definition in enum, C#

I am trying to compare values that I am getting from web service, but sometimes I get int value, sometimes i get string. So it would be great that i could only check for Type.value1.
for example:
enum Type { value1 = 1 , value1="one"}
and like that for more value2, etc...
But of course, I cannot do this because it I cannot add two definitons for value1.
Sometimes a type that behaves mostly like an enum but has some richer behaviour can be very useful:
public sealed class MyFakeEnum {
private MyFakeEnum(int value, string description) {
Value = value;
Description = description;
}
public int Value { get; private set; }
public string Description { get; private set; }
// Probably add equality and GetHashCode implementations too.
public readonly static MyFakeEnum Value1 = new MyFakeEnum(1, "value1");
public readonly static MyFakeEnum Value2 = new MyFakeEnum(2, "value2");
}
You can consider adding attributes to the enums and use reflection.
enum Type
{
[Description("One")]
value1 = 1
}
I also make use of using decorating the enum with a description attribute as described by BSoD_ZA. But I would suggest that you then implement an extension method for the enumeration to obtain the string description for example:
public static class EnumExtension
{
public static string ToDescription<TEnum>(this TEnum enumValue) where TEnum : struct
{
return ReflectionService.GetClassAttribute<DescriptionAttribute>(enumValue);
}
}
enum Type
{
[Description("One")]
value1 = 1
}
var value = Type.Value1;
Console.Writeline(value.ToDescription());

System.ComponentModel.DescriptionAttribute in portable class library

I am using the Description attribute in my enums to provide a user friendly name to an enum field. e.g.
public enum InstallationType
{
[Description("Forward of Bulk Head")]
FORWARD = 0,
[Description("Rear of Bulk Head")]
REAR = 1,
[Description("Roof Mounted")]
ROOF = 2,
}
And accessing this is easy with a nice helper method:
public static string GetDescriptionFromEnumValue(Enum value)
{
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
I need to convert this into a portable class library but it doesn't seem to have access to the System.ComponentModel library. when I try add a reverence VS tells me that I have referenced everything already.
Thanks
Since DescriptionAttribute is not available for portable class libraries you need to use another attribute. The namespace System.ComponentModel.DataAnnotations which is available for portable class libraries provides the attribute DisplayAttribute that you can use instead.
public enum InstallationType
{
[Display(Description="Forward of Bulk Head")]
FORWARD = 0,
[Display(Description="Rear of Bulk Head")]
REAR = 1,
[Display(Description="Roof Mounted")]
ROOF = 2,
}
Your method needs to be changed to
public static string GetDescriptionFromEnumValue(Enum value)
{
DisplayAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(DisplayAttribute ), false)
.SingleOrDefault() as DisplayAttribute ;
return attribute == null ? value.ToString() : attribute.Description;
}
Whether something is available to a portable class library depends a bit on exactly which frameworks you selected for the library - you get the strict intersection only. However, it could well be that this attribute simply doesn't exist in one of your targeted frameworks. In which case, one option is add your own - then you know it is available. For example:
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumDescriptionAttribute :Attribute
{
private readonly string description;
public string Description { get { return description; } }
public EnumDescriptionAttribute(string description)
{
this.description = description;
}
}
enum Foo
{
[EnumDescription("abc")]
A,
[EnumDescription("def")]
B
}
Note that I intentionally haven't included the additional serialization construtors here, because those too depend on features that are not available on all frameworks. Changing your code from using [Description] / DescriptionAttribute to [EnumDescription] / EnumDescriptionAttribute should be fairly trivial.
Try this for retrieving attribute for enum in portable libraries:
public static class EnumsHelper
{
public static T GetAttributeOfType<T>(this Enum enumVal) where T : Attribute
{
var typeInfo = enumVal.GetType().GetTypeInfo();
var v = typeInfo.DeclaredMembers.First(x => x.Name == enumVal.ToString());
return v.GetCustomAttribute<T>();
}
}
Update: also you should declare new attribute (look like DescriptionAttribute not available in PCL), for example next:
public class MyDescriptionAttribute : Attribute
{
public virtual string Text { get; set; }
}
and add one more method in EnumsHelper class:
public static class EnumsHelper
{
...
public static string GetDescription(this Enum enumVal)
{
var attr = GetAttributeOfType<MyDescriptionAttribute>(enumVal);
return attr != null ? attr.Text : string.Empty;
}
}
and if you have next enum:
public enum InstallationType
{
[MyDescription(Text = "Forward of Bulk Head")]
FORWARD = 0
}
you can retrieve description with code like this:
static void Main(string[] args)
{
var it = InstallationType.FORWARD;
var description = it.GetDescription();
Console.WriteLine(description);
}

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
}

Categories