Generic Enum as Type [closed]

Are generic types of enum possible in C#? I’m trying to do something like this:

// in LevelManager.cs script public class LevelManager<T>  where T : struct {     public T something; }  // in enum script (name to be changed accordingly) public enum Level { A,B,C }  // in LevelManager2.cs public class LevelManager2<Level> : LevelManager<Level>{} 

I’m asking this question mainly because the implementation for the generic class LevelManager will be hidden away in an assembly. Hence, I have to rely on something the next person would code the enum Level in. I also get this error in my test script: pic

Alternatively, I could opt for a string based method where the string is the key and I’ll have a Dictionary<string,int>. But that would require a rewriting of my entire script

Any help on how to retain an enum like structure?

Mysql: Any way to properly index 3 ENUM columns with the same options ? (A OR B OR C)

I have 3 enum() columns with the same option values inside.
I first tried to use the "set" datatype which originally was meant to do that (hold multiple values from a set) but it seems that datatype isn’t managed for 15+ years and isn’t even supporting an index.
Is there a nice way to index those 3 columns so I can use them in searched without destroying query performance ?

SELECT * FROM TABLE WHERE a=’x’ OR b=’x’ OR c=’x’

I thought about creating a virtual field which uses a boolean logic (&) on the 3 enum field-numbers and combines them into a large number but that’s quite a hack and not nice to maintain.

Has someone solved this sort of task elegantly ? (I do not want to use a support table and JOIN it, I want to stay with a single table)

Separate table or a enum on a client?

I have several tables and many of them has a “status”, “measure_unit” and the like columns in them.

There’re 2 approaches to work with columns such as “status”.

  1. Create separate tables “statuses”, “measure_units” in database and reference to them from the main tables via a foreign key. Either by string/slug or by id. That is, these “statuses”, “measure_units” tables are ones with at most 10 records in them and they will be rarely modified.

  2. Create enums/structs “statuses”, “measure_units” on a client.

They both have their up- and downsides.

Which is more and better in different ways approach?

Como gravar um enum no banco de dados com JPA e postman

Estou criando um cadastro de produtos, e quando passo pelo Postman o JSON de meu produto para ser gravado, o seu tipo está sendo salvo como NULL.

Os tipos dos produtos são um enum, vou colocar abaixo o código que tentei utilizar para gravar os tipos. Estou fazendo algo de errado? Devo passar o JSON de outra forma? Agradeço pela ajuda

Código do Enum :

public enum TipoProduto {      INFORMATICA(1, "informatica"), ELETRONICOS(2, "eletronicos"), CAMA(3, "cama"), MESA(4, "mesa"), BANHO(5, "banho"), CALCADOS(6, "calcados");       private String descricao;     private Integer codigo;      private TipoProduto(Integer codigo, String descricao) {         this.codigo = codigo;         this.descricao = descricao;     }      public String getDescricao() {         return descricao;     }      public Integer getCodigo() {         return codigo;     } } 

Forma como estou tentando passar o JSON no POSTMAN:

{     "nome": "Notebook",     "TipoProduto": 1,     "valor": 1300.00,     "cor": "Cinza Fosco",     "especificacoes": "8GB RAM, i7, 256GB" } 

Enum design: when an “open” set would be acceptable as enum’s values?

I was looking into the Enum design recommended by Microsoft (see here), and I found a statement that made me stop to think for a while:

X DO NOT use an enum for open sets (such as the operating system version, names of your friends, etc.).

It says that OS versions are considered as open set, therefore it should not be enumerated. Moving forward with my doubt: I’m developing a proxy to an API, and I’m thinking in allow the proxy’s consumers choose the API version. The approach that I got in mind it’s just define an enum that lists all the API versions, thus consumers are allowed to pass which API version they want to use.

However, due to API versions is something that would be considered as open (eventually there will be more versions), I’m doubting in include the version choosing feature. So, does this guideline not fit in my scenario?

Using enum for singleton implementations to choose way of doing something

I have this service that reads emails from a mailbox as they come and I want to extract its contents in a map structure. For now I am interested only in the actual email (no images or attachments).

I started by using an enum when I wanted something simple and then extended the enum to implement an interface when I noticed that I needed some complexity and at the end because the method extracting the content was a few lines long and the enum was getting hard to read I extracted the implementation to their own interface implementations and just assigned an instance of each in the enum.

It doesn’t feel wrong, I actually think that this is what Spring looks like (very simply for conceptual purposes) when it creates singletons for autowiring but wanted to get an opinion by the community and if this is a valid approach, is there something I missed or something to consider

This is the interface of the extractor with a default method for something that is common to the implementations

public interface ContentExtractor {     Map<String, String> extract(Message mimeMessage) throws IOException, MessagingException;      default String extract(BodyPart bodyPart) {         try {             return (String)bodyPart.getContent();         }         catch (IOException | MessagingException e) {             LOGGER.warn("Couldn't cast part to a String. It's either a multipart body part or probably a content type that resolves to a stream.");             return null;         }     } } 

The abstract class for a base. I am actually divided on whether I need this, I don’t actually remember why I added it…

@Getter public abstract class MimeContentExtractor implements ContentExtractor {     private final String mimeType;     MimeContentExtractor(String mimeType) {this.mimeType = mimeType;}      static String getContentType(Part part) {         try {             return part.getContentType();         } catch (MessagingException e) {             LOGGER.warn("Couldn't get the content type of the part");             return "N/A";         }     } } 

The enum

@Getter public enum MimeType {     MULTIPART(new MultipartContentExtractor("multipart/")),     TEXT(new TextContentExtractor("text/plain")),     HTML(new TextContentExtractor("text/html"));      private final MimeContentExtractor contentExtractor;      MimeType(MimeContentExtractor contentExtractor) {         this.contentExtractor = contentExtractor;     }      public static Optional<MimeContentExtractor> getExtractor(Part part) {         return determineMimeType(part)                 .map(MimeType::getContentExtractor);     }      private static Optional<MimeType> determineMimeType(Part part) {         return Arrays.stream(values())                 .filter(ct -> ct.matchesContentType(part))                 .findFirst();     }      private boolean matchesContentType(Part part) {         try {             return part.getContentType().startsWith(getMimeType());         } catch (MessagingException e) {             LOGGER.warn("Failed to determine content type of {}", part);             return false;         }     }      public String getMimeType() {         return contentExtractor.getMimeType();     } } 

I have two implementations for content. The text/plain and text/html just override extract and return the content forcing it to be a string (Java mail, this is how it works) and the multipart/mixed is a bit more complex but basically goes through the parts, and uses the enum again to determine what extractor to use. For now it will recognise the text and use the aforementioned implementations.

public class MultipartContentExtractor extends MimeContentExtractor {     MultipartContentExtractor(String mimeType) {         super(mimeType);     }      @Override     public Map<String, String> extract(Message mimeMessage) throws IOException, MessagingException {         Multipart content = (Multipart)mimeMessage.getContent();         return extract(content);     }      private Map<String, String> extract(Multipart content) throws MessagingException {         int numberOfBodyParts = content.getCount();         LOGGER.info("The content has {} parts", numberOfBodyParts);          Map<String, String> bodyPartContents = new HashMap<>();         IntStream.range(0, numberOfBodyParts)                 .boxed()                 .peek(i -> LOGGER.info("Attempting to get body part {}", i))                 .map(wrapWithOptional(content::getBodyPart))                 .peek(bp -> LOGGER.info("Body part was {} retrieved", bp.isPresent() ? "" : "not"))                 .filter(Optional::isPresent)                 .map(Optional::get)                 .forEach(bodyPart -> {                     LOGGER.info("Content type of body part is {}", getContentType(bodyPart));                     MimeType.getExtractor(bodyPart)                             .ifPresent(ce -> bodyPartContents.put(ce.getMimeType(), ce.extract(bodyPart)));                 });         return unmodifiableMap(bodyPartContents);     } }  @Getter public class TextContentExtractor extends MimeContentExtractor {     TextContentExtractor(String mimeType) {         super(mimeType);     }      @Override     public Map<String, String> extract(Message mimeMessage) throws IOException, MessagingException {         return singletonMap(getMimeType(), (String)mimeMessage.getContent());     } } 

Finally this is how it is used

@Component public class BackofficeMailProcessor implements Processor {     ...     @Override     public void process(Exchange exchange) {         MailMessage mailMessage = (MailMessage)exchange.getMessage();          Map<String, String> contents = getContents(mailMessage);         if (contents.isEmpty()) {             throw new BackofficeMailProcessorException("Couldn't get any of the contents of the email. Stopped processing!");         }         ...     }      private Map<String, String> getContents(MailMessage mailMessage) {         final Message mailMessageBody = mailMessage.getMessage();         Optional<MimeContentExtractor> extractor = MimeType.getExtractor(mailMessageBody);         if (extractor.isPresent()) {             try {                 return extractor.get().extract(mailMessageBody);             }             catch (IOException | MessagingException e) {                 LOGGER.error("Failed to extract contents of email", e);             }         }          return emptyMap();     }     ... } 

The fact that is an enum doesn’t make it optimal for unit testing. This is part of a larger project and I did something similar for extracting reply for different kind of email clients (yahoo, gmail, etc) but there I also made a factory where I used the enum in the supplier (not a static one) and wired the factory where I would use the Enum in the above example.

How to improve a pattern ‘enum class with methods’

Over many years, I always find myself reconsidering this design, so I wanted to get some feedback on my solution to it.

Problem:

I need a limited amount of objects = instances from a class, and I don’t want to expose the option to create more. I also want easy access to them from everywhere, and operators like equal / not equal.
They need to be class instances, as they need to have methods, so a enum doesn’t work.

(Simplified) Example:

Consider for example any chess-like game.

  1. There are three tile colors for the board needed, Lighter and Darker, and a different size tile where taken pieces are put. Also,
  2. the pieces have a color, typically White or Black; and I use NoColor for empty fields.

Both examples, each instance should know how to draw and serialize itself.

Obvious Option:

If I make a simple enum, the values cannot carry methods, so I end up with Draw and Serialize methods in some other class, which are basically an ugly switch/case.

My Solution:

I like to

  1. protect the constructor, and,
  2. create (public) static instances inside the class (C++17 now allows that even directly with inline).

‘Each instance gets created with a const ‘type’ in it (basically a enum), set through the constructor.
Wherever I need the information, I use the const pointer to that static instance. This allows to easily _compare and assign them, and also allows calling their member functions as needed.
It even allows other games to derive from the class and add new static instances, for example, a three-player chess could add a Red instance inside a derived class. Because I hand around pointers to the base class everywhere, it is polymorphic, and the code doesn’t have to handle the new color special in any way…

class Color { protected:   Color(char c) : color{c} {} public:   void Serialize(Archive& ar) const { ar << color; }  private:   const char color;  public:  // the only instances ever to exists; handed around by pointer   inline const static Color NoColor{'X'};   // C++17 syntax, otherwise   inline const static Color White{'W'};     // separate line in .cpp needed   inline const static Color Black{'B'}; };  class Chess3Color : public Color { protected:   Chess3Color(char c) : Color{c} {}  public:   inline const static Chess3Color Red{'R'}; }; 

Example Usage:

... // create a White King Piece* p = new WhiteKing{&Type::King, &Color::White, IDB_W_K_BMP}; ... if (p->IsColor(&Color::White)) { ... } ... p->Serialize(ar); ... class Piece {   ...   // Piece member function for serialization   void Serialize(Archive& ar)   {     type->Serialize(ar);     color->Serialize(ar);   }   ...   // check if this piece is of a certain color   // note that pointer compare is good enough!   bool IsColor(const Color* c) { return color == c; }   ... } 

Question:

I go back and forth in my mind between this being a code smell or a pretty good and clean solution. So is it a code smell?
How else would this be better designed?

I have read a lot about Singletons, and I don’t think they would do me any good (aside from the fact that some people think they are a code smell too).

Obtener la descripción de un Enum en una consulta linq

Trabajo con C#, Visual Studio 2019 Tengo la siguiente consulta

var result = from ov in context.OrdenVentas                          join c in context.Clientes on ov.ClienteId equals c.ClienteId                          where                              (filter.Codigo == null || ov.CodigoNumerico.Contains(filter.Codigo))                              &&                              (!filter.ClienteId.HasValue || ov.ClienteId.Equals(filter.ClienteId.Value))                              &&                              (filter.FechaEmision == null || ov.FechaEmision >= filter.FechaEmision)                              &&                              (filter.FechaCaducidad == null || ov.FechaCaducidad <= filter.FechaCaducidad)                              &&                              ov.Estado == EstadoOrdenVenta.Emitido                          select                              new UniversalExtend()                              {                                  Id = ov.OrdenVentaId,                                  NumeroComprobante = ov.NumeroComprobante,                                  Descripcion = c.RazonSocial,                                  FechaEmision = ov.FechaEmision,                                  FechaCaducidad = ov.FechaCaducidad,                                  Estado =                                   Total = ov.Total                              };             return result.ToList(); 

En estado necesito obtener la descripción de un enum.

En el campo estado(en la db) tengo los valores del enum ahora quiero recuperarlo en una variable estado de tipo string, ¿como puedo leer la descripcion de un enum pasandole un campo ov.Estado el cual tiene el id del enum?

public enum EstadoOrdenVenta : int {     [Description("EMITIDO")]     Emitido = 1,     [Description("APROBADO")]     Aprobado = 2,     [Description("ATENDIDO")]     Atendido = 3 } 

Solo quiero obtener lo que esta en minúscula.

kongchen/swagger-maven-plugin enum generation

i’m having hard times generating proper swagger 2.0 yaml documentation using kongchen swagger-maven-plugin. My problem happens when have 2 classes using same enum class.

public enum Enum {    A,B,C }  public class First {    public Enum e; }  public class Second {    public Enum e; } 

This will generate swagger.yaml file containing:

definitions:   First:     type: "object"     properties:       e:         type: "string"         enum:         - "A"         - "B"         - "C"   Second:     type: "object"     properties:       e:         type: "string"         enum:         - "A"         - "B"         - "C" 

However, I would like it to generate just one enum model definition and reference the type in objects’ fields. Something like this:

definitions:   First:     type: "object"     properties:       $  ref: "#/definitions/Enum"    Second:     type: "object"     properties:       e:         $  ref: "#/definitions/Enum"    Enum:     type: "string"     enum:         - "A"         - "B"         - "C" 

Is there any way to achieve this? This way my generated client generates multiple inner enum classes with same values.

Thanks.