How to convert Enum to string?

Asked

Viewed 71 times

0

Hello, I want to list the elements of the class called, but the Status is of type Enum, when trying to convert to string, appears the message: "It is not possible to implicitly convert type 'string' into Enums.Status". Code:

public async Task<IEnumerable<ChamadoViewModel>> ObterTodos()
    {
        var chamados = await _repository.ObterTodos();
        var chamadosView = new List<ChamadoViewModel>();

        foreach(var chamado in chamados)
        {
            chamadosView.Add(new ChamadoViewModel
            {
                IdOrigemUsuario = chamado.IdOrigemUsuario,
                IdUsuario = chamado.IdUsuario,
                IdOperadora = chamado.IdOperadora,
                DataChamado = chamado.DataChamado,
                HoraChamado = chamado.HoraChamado,
                Solicitadora = chamado.Solicitadora,
                NomeProfissional = chamado.NomeProfissional,
                Motivo = chamado.Motivo,
                Erro = chamado.Erro,
                Status = chamado.Status.ToString()
            });
        }
    }
  • "Cannot implicitly convert string to Enums.Status" by the message, in that ChamadoViewModel the Property Status is an Enum and not string, hence it is giving error. It puts the definition of the class in the question and also of the class that is the type of the variable chamados, but I think you need to convert one One to another One. If they have the same values, it could convert to int before, but if they are different, and this would be the most recommended, would be to make a method that maps the values

  • @fanwraunes something new?

1 answer

2

In the example below I convert String to Enum and vice versa. I hope I helped.

using System;

namespace TestVoid
{
    class Program
    {
        static void Main(string[] args)
        {
            var placeStr = "Home";

            var place = Places.School;

            Console.WriteLine(place);

            // Enum to String.
            placeStr = place.ToString();

            // String to Enum.
            // Enum.TryParse<Places>(placeStr, true, out place);

            Console.WriteLine(placeStr);
        }

        public enum Places{
            Home, Work, School
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.