1

Please refer to the below-given code snippet

foreach (var invoiceDescription in qbInvoiceLineArray)
{
    Line lineDescription = new Line();
    lineDescription.Description = Convert.ToString((string)invoiceDescription.SelectToken(QBConfig.InvoiceDescription));
    invoice.Line.Add(lineDescription);             
} 
    
public class QbInvoiceViewModel
{
    public decimal Balance { get; set; }       
    public List<LinkedTxn> LinkedTxn { get; set; }
    public DateTime DueDate { get; set; }
    public DateTime TxnDate { get; set; }
    public Decimal TotalAmt { get; set; }
    public List<Line> Line { get; set; }    
}
    
public class Line
{
    public string Description { get; set; }
    public LineDetailTypeEnum DetailType { get; set; }
}
    
public enum LineDetailTypeEnum
{
    SalesItemLineDetail
}

This line of code

lineDescription.Description = Convert.ToString((string)invoiceDescription.SelectToken(QBConfig.InvoiceDescription));

can be used to convert string to string in c#. This type of code can be used to convert string to int also in c#. But how this type of code can be used to convert string to enum?

ThomasArdal
  • 4,999
  • 4
  • 33
  • 73
Isuru 99
  • 5
  • 5
  • Why are you using `Convert.ToString` with `String` arguments? – Dai Mar 15 '21 at 05:45
  • Does this answer your question? [Convert a string to an enum in C#](https://stackoverflow.com/questions/16100/convert-a-string-to-an-enum-in-c-sharp) – JHBonarius Mar 15 '21 at 09:43

1 Answers1

1

You don't use Convert.ToString to strings to other things, you use Convert.ToXxx

If invoiceDescription.SelectToken(QBConfig.InvoiceDescription) is returning you a string (or an object that is actually a string, as your cast might indicate) of the enum member name or value, and you want it converting to a particular enum, you should Enum.Parse<T> it, like var e = Enum.Parse<InvoiceToken>((string)invoiceDescription.SelectToken(QBConfig.InvoiceDescription)), of course replacing InvoiceToken with the actual name of your enum

If invoiceDescription.SelectToken(QBConfig.InvoiceDescription) is returning you an int that is the enum member value (not the name) you can also alternatively Convert.ToInt32() it and then cast it to the enum type; any int can be cast to an enum

MSDN for enum parse

(It's probably also worth noting that Enum.Parse<T> is more recent than other forms; if youre on an older version of .NET you're looking at something more like (T)Enum.Parse(typeof(T), string_here))

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • To add to the string to int part, [there are more options, like Parse and TryParse](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number) – JHBonarius Mar 15 '21 at 09:38
  • Ineed, though I wasn't aiming to make this answer an exhaustive list of how to convert a string to an int, because the focus is on enums – Caius Jard Mar 15 '21 at 11:15