user4970927
user4970927

Reputation: 179

Converting Enum for use in a class

Below I have a piece of code I have been working on for quite sometime:

 enum SavingsIndicator
 {
   OKSavings,
   GoodSavings,
   GreatSavings,
 }

static void Main(string[] args)
{

 foreach (string line in gdsLines)
        {

            Match m = Regex.Match(line, @"^(?<date>[^|]+)\|.*Processed\s+(?<locator>[^.]+)\.{3}.*?Savings\s+found:\s*\$(?<savings>\d+\.\d+)\s*\(\s*(?<percent>\d+\.\d+)\s*%");
            if (m.Success)
            {
                Savings s = new Savings();
                s.Prefix = string.Empty;
                s.GDSDate = m.Groups["date"].Value.Trim();
                s.GDSLocator = m.Groups["locator"].Value.Trim();
                s.GDSDollarSavings = decimal.Parse(m.Groups["savings"].Value, CultureInfo.InvariantCulture);
                s.GDSPercentSavings = decimal.Parse(m.Groups["percent"].Value, CultureInfo.InvariantCulture);

                gdsSavings.Add(s);
                gdsTotalSavings += s.GDSDollarSavings;
                gdsTotalPercentage += s.GDSPercentSavings;
 if (s.GDSDollarSavings >= 500)
                {
                    s.Prefix = SavingsIndicator.GreatSavings;
                }
                else if (s.GDSDollarSavings >= 100 && s.GDSDollarSavings < 500)
                {
                    s.Prefix = SavingsIndicator.GoodSavings;
                }
                else
                {
                    s.Prefix = SavingsIndicator.OKSavings;
                }
            }

        }
        foreach (var savings in gdsSavings.OrderByDescending(savingsInstance => savingsInstance.GDSDollarSavings))
        {
            Console.WriteLine(savings.ToString());

        }
    }
   }

Below is the class that I have for this to work:

class Savings
{
    public string Prefix { get; set; }
    public string GDSDate { get; set; }
    public string GDSLocator { get; set; }
   public decimal GDSDollarSavings { get; set; }
   public decimal GDSPercentSavings { get; set; }

   public override string ToString()
   {
       return Prefix + "\nDate: " + GDSDate + " \nPNR Locator: " + GDSLocator + " \nDollar Savings: $" + GDSDollarSavings + " \nPercent Savings: " + GDSPercentSavings + " % " + "\n";
   }
}

The problem I am having is where I have the prefixes. I want those enumerated values to be in the Prefix variable of my class, but I can't convert my enumerated values to a string. Is there a way to successfully convert this into a string, or is there another way to go around this?

Upvotes: 0

Views: 94

Answers (3)

ΩmegaMan
ΩmegaMan

Reputation: 31576

or is there another way to go around this?

One can add an Attribute to enums and then extract them at runtime. One can also create custom attributes with even more information.

Here is my example from my blog article Using Extended Attributes which uses the built in System.ComponentModel's Description attribute.

Example

public enum EPortalErrors
{

  [Description("Internal programming error")]
  InternalError,

  [Description("Invalid request Xml: Reset XSLT.")]
  InvalidXmlSentIn,

}

Static method to extract the description text:

/// <summary>If an attribute such as is on an enumeration exists, this will return that
/// information</summary>
/// <param name="value">The object which has the attribute.</param>
/// <returns>The description string of the attribute or string.empty</returns>
public static string GetAttributeDescription( object value )
{
    string retVal = string.Empty;
    try
    {
        FieldInfo fieldInfo = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
           (DescriptionAttribute[])fieldInfo.GetCustomAttributes
           (typeof(DescriptionAttribute), false);

        retVal = ( ( attributes.Length > 0 ) ? attributes[0].Description : value.ToString() );
    }
    catch (NullReferenceException)
    {
     //Occurs when we attempt to get description of an enum value that does not exist
    }
    finally
    {
        if (string.IsNullOrEmpty(retVal))
            retVal = "Unknown";
    }    

    return retVal;
}

Usage

var msg = EPortalErrors.InternalError.GetAttributeDescription();

// Result "Internal programming error" assigned to msg.

See my blog article as mentioned for an example on how to create custom attributes to add even more info.

Upvotes: 0

Alex H
Alex H

Reputation: 1503

How about writing an Extension Method:

static class ExtensionMethods
{
    public static string AsString(this SavingsIndicator self)
    {
        switch(self)
        {
            case SavingsIndicator.OKSavings:
                return "OKSavings"
               case GoodSavings:
                return "GoodSavings"
               case GreatSavings:
                return "GreatSavings"
        }
        return string.Empty
    }
}

In Addition your other Medhod has to be modified:

            {
                s.Prefix = SavingsIndicator.GreatSavings.AsString();
            }
            else if (s.GDSDollarSavings >= 100 && s.GDSDollarSavings < 500)
            {
                s.Prefix = SavingsIndicator.GoodSavings.AsString();
            }
            else
            {
                s.Prefix = SavingsIndicator.OKSavings.AsString();
            }

Upvotes: 0

Brant Olsen
Brant Olsen

Reputation: 5664

You can do one of two things.

1) Just call .ToString() on the enum value which will convert it to a string with the exact same value as what you named the enum, so OKSavings becomes "OKSavings".

2) Create a method public string Format(SavingsIndicator e) that returns a pretty string describing the enum.

Upvotes: 1

Related Questions