Site Logo
How to get girlfriend or boyfriend > 50 years > C# enum friendly name attribute

C# enum friendly name attribute

Feb C and. NET , Geeks , Programming. It came about in MVC project I was working on that we wanted to output friendly names for a large number of enumerations we were working on directly into a selectable dropdown list. We would have an enum on a ViewModel object and that would be automatically put into a combo box with the selected item shown. Because alot of our model was pre-generated and we were getting these models from XML serialisation we ended up with a bunch of Enums defined like so.

SEE VIDEO BY TOPIC: Quick Tip: Use Enums for State handling (Unity Tutorial)

Content:
SEE VIDEO BY TOPIC: C# Flags Enum Explained - Deep Dive

Show User Friendly Enum Value Into The Combobox

By using our site, you acknowledge that you have read and understand our Cookie Policy , Privacy Policy , and our Terms of Service. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Enum value names must follow the same naming rules as all identifiers in C , therefore only first name is correct. You could use the Description attribute, as Yuriy suggested.

The following extension method makes it easy to get the description for a given value of the enum:. You can declare Extension Methods for MyEnum like you can for any other type. I just whipped this up:. No, but you can use the DescriptionAttribute to accomplish what you're looking for. You can use the Description attribute to get that friendly name.

You can use the code below:. An example of when you would want to use this method: When your enum value is EncryptionProviderType and you want enumVar. Tostring to return "Encryption Provider Type". Prerequisite: All enum members should be applied with the attribute [Description "String to be returned by Tostring " ].

One problem with this trick is that description attribute cannot be localized. I do like a technique by Sacha Barber where he creates his own version of Description attribute which would pick up values from the corresponding resource manager. Although the article is around a problem that's generally faced by WPF developers when binding to enums, you can jump directly to the part where he creates the LocalizableDescriptionAttribute.

Some great solutions have already been posted. When I encountered this problem, I wanted to go both ways: convert an enum into a description, and convert a string matching a description into an enum. I have two variants, slow and fast. Both convert from enum to string and string to enum. My problem is that I have enums like this, where some elements need attributes and some don't. I don't want to put attributes on elements that don't need them.

I have about a hundred of these total currently:. The first method for dealing with this is slow, and is based on suggestions I saw here and around the net. It's slow because we are reflecting for every conversion:. The problem with this is that you're doing reflection every time. I haven't measured the performance hit from doing so, but it seems alarming. Worse we are computing these expensive conversions repeatedly, without caching them. Instead we can use a static constructor to populate some dictionaries with this conversion information, then just look up this information when needed.

Apparently static classes required for extension methods can have constructors and fields :. Look how tight the conversion methods are now. The only flaw I can think of is that this requires all the converted enums to be in the current assembly. Also, I only bother with exported enums, but you could change that if you wish. After reading many resources regarding this topic, including StackOverFlow, I find that not all solutions are working properly. Below is our attempt to fix this.

Basically, We take the friendly name of an Enum from a DescriptionAttribute if it exists. If it does not We use RegEx to determine the words within the Enum name and add spaces. Enum names live under the same rules as normal variable names, i. I still consider the first one to be rather friendly though Your enum names must have the same number of characters or more than the string that you want to it to be.

NET week. I suppose that you want to show your enum values to the user, therefore, you want them to have some friendly name. Learn more. Can my enums have friendly names? Asked 10 years, 8 months ago. Active 1 year, 5 months ago. Viewed k times. Default What's unfriendly about ThisNameWorks? Dudley Sep 12 '09 at It's "unfriendly" because he probably wants to be able to display the enum name on a form or webpage, but can't because there are no spaces.

ChaseMedallion I might be blind but I can't see anything about friendly names in that blog post. Michael check out the part at the end about using Attributes to attach descriptions or other metadata to enums.

Active Oldest Votes. RaYell RaYell You can use the System. DataAnnotations and add an display attr. Cas's comment is effectively the solution most use these days. CasBloem not works anymore.

CasBloem Just in case anyone is trying to use Display in an old version of. NET, it's only supported as far back as. NET 4. Answer by Thomas Levesque should be set as the accepted answer. GetName type, value ; if name! GetField name ; if field! GetDescription ;. Lauren Van Sloun 1, 5 5 gold badges 15 15 silver badges 19 19 bronze badges. Thomas Levesque Thomas Levesque k 58 58 gold badges silver badges bronze badges.

I'm planning to add support for this into UnconstrainedMelody tonight. So annoying when posts don't include the non-default namespaces that they reference ComponentModel and System. Visual Studio can add them automatically with just 2 clicks This should be accepted as the answer instead of the currently accepted one. ThomasLevesque often times multiple namespaces match esp with a generic class like Description.

WriteLine MyEnum. EnumValue ; Hope this helps!! Mark Carpenter Mark Carpenter Keep in mind that the switch statement is effectively a linear search with complexity O n -- the worst case requires comparison with very value in the enum. Roy - that's not always true, sometimes precisely when is based on an implementation detail the C compiler will emit a Dictionary lookup instead, see: stackoverflow. John - Thanks for the info, I did not know that! I'll have to look that up. Roy, I could be wrong here, but I was under the impression that that is not true.

For instance, if you're switching off of a byte value, I think it will most likely just emit a jump table. Yuriy Faktorovich Yuriy Faktorovich GetMember en. ToString ; if memInfo! GetCustomAttributes typeof DescriptionAttribute , false ; if attrs! ValueOne; Console. Trainee4Life Trainee4Life 2, 1 1 gold badge 19 19 silver badges 38 38 bronze badges.

Description " " ] Hash, [System. Description "''" ] DoubleTick, [System. Description " " ] LeftParenth, [System. Description " " ] RightParenth, [System.

Description "," ] Comma, [System. Description ". Description ":" ] Colon, [System. It's slow because we are reflecting for every conversion: using System; using System. GetCustomAttribute field, typeof System.

DescriptionAttribute as System.

C# stuff nobody told you – enum is a b*tch!

Specifies the display name for a property, event, or public void method which takes no arguments. The following code example demonstrates using the DisplayNameAttribute class to change the name of a property called MisnamedProperty to RenamedProperty in a PropertyGrid control. The default is the name of the property or event. The default implementation of GetSortedActionItems uses reflection to search the public properties and public void methods that take no arguments. GetSortedActionItems searches for the DisplayNameAttribute on each property and method and, if found, uses that string instead of the property or method name.

When working with enums in C , it is sometimes necessary to get a string description of the value associated with the enum. This can be accomplished easily by using the DescriptionAttribute class. Originally, I was using code like the following to set the string value based on the value of an enum, but it seemed too cumbersome and had to be used everytime I wanted to parse an enum.

An Enumeration or enum is a data type that includes a set of named values called elements or members. The enumerator names are usually identifiers that behave as constants in the language. Sometimes you might need to loop on the elements of a particular enum and print its element names, however as you know by the language constraints, the enum element names must follow the naming convention, you cannot include spaces or other special characters. Therefore printing the elements will lead to printing the defined non-friendly elements names.

How to Display Friendly Names for Enumerations in C#?

GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together. Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community. Already on GitHub? Sign in to your account. This would also be tricky DisplayAttribute is part of System. DataAnnotations or System. Annotations depending on your platform, but Enum. Runtime could be OK too , the important thing is that should be a way to do this without the need to it "manually" anytime.

Creating user friendly strings for C# enums

Comment 0. The Java Enum has two methods that retrieve that value of an enum constant, name and toString. The toString method calls the name method, which returns the string representation of the enum constant. In listing 1, the value returned by calling the name and toString on an Animal.

To print the enumeration elements names, we will iterate over the names of the Enumeration type, append each name to a string builder and then display it on a message box, see the below code snippet:.

If you develop using C and the. Net ecosystem, chances are that you will need to use enums at a certain point. The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

Giving an Enum a String Value Using the Description Attribute

I want to be able to output these values in a user friendly way though. I don't need to be able to go from string to value again. I use the Description attribute from the System.

In my previous article, we have learned that how to bind combobox directly with enum. In my previous article , we learned how to bind a combobox directly with the enum. So here, we will learn a way to show user-friendly enum names to end users. Please note that here, I have considered the implementation mentioned in the previous article, so please check that first before going further. Now, we will implement IValueConverter to display enum description instead of enum value. For that, create a class called EnumDescriptionConverter as mentioned below.

Getting friendly names from an Enum when decorated with multiple attribute

For the first article, I will show you how friendly looking, always helpful, good guy enum can become an asshole. An asshole who will steal your precious time! The situation was strange… We have a method that takes our enum as a parameter and processes it somehow. We passed as a parameter OurEnumType. Tl;dr; To fully understand the situation, have a look at the method below. It just reads the enum description straight from the [Description] attribute.

Mar 26, - So you might ask how can I display friendly names for enumerations in new Description attribute decoration applied to the enum names: C#.

The following example shows EnumMemberAttribute applied to members of an enumeration. The EnumMemberAttribute enables fine control of the names of the enumerations as they are serialized. Then apply the EnumMemberAttribute attribute to each member that needs to be in the serialization stream. Initializes a new instance of the EnumMemberAttribute class. Gets whether the Value has been explicitly set.

User Friendly Display Text For Enum in C#

An Enumeration or enum is a data type that includes a set of named values called elements or members. The enumerator names are usually identifiers that behave as constants in the language. Sometimes you might need to loop on the elements of a particular enum and print its element names, however as you know by the language constraints, the enum element names must follow the naming convention, you cannot include spaces or other special characters. Therefore printing the elements will lead to printing the defined non-friendly elements names.

Smart enums / Type-safe enums in .NET

By using our site, you acknowledge that you have read and understand our Cookie Policy , Privacy Policy , and our Terms of Service. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Enum value names must follow the same naming rules as all identifiers in C , therefore only first name is correct.

Sanity Free Coding Methods to the Madness.

.

Enum: Using the Name() and toString() Methods Correctly

.

.

Comments: 5
  1. Fauzil

    I consider, that you commit an error. I can defend the position.

  2. Zololabar

    In my opinion the theme is rather interesting. Give with you we will communicate in PM.

  3. Tekree

    And how in that case to act?

  4. Gardam

    Between us speaking, I would arrive differently.

  5. Nanris

    In my opinion you are not right. I am assured. I can prove it. Write to me in PM, we will discuss.

Thanks! Your comment will appear after verification.
Add a comment

© 2020 Online - Advisor on specific issues.