TheEdge
TheEdge

Reputation: 9851

Array of strings "subscripted" by an enum in C#

This is a hang over from my Delphi days where I was able to do something as follows:

  type
   TCars  = (Ford, Nissan, Toyota, Honda);     
  const
      CAR_MODELS = array[TCars] of string = ('Falcon','Sentra','Camry','Civic');

which allowed me to an enumeration declartively with some associated data. In this case a string but it could have been a record structure or similair. It meant that if I added a member to TCars and forgot to update the CAR_MODELS array I would get a compile time error.

What is the C# approach to this? I have tried:

public enum ReportFileGeneratorFileType
{
    Excel,
    Pdf,
    Word
}

string[ReportFileGeneratorFileType] myArray = {"application/vnd.ms-excel", "application/pdf", "application/vnd.ms-word"};

but that does not appear to compile.

Upvotes: 1

Views: 171

Answers (3)

BrunoLM
BrunoLM

Reputation: 100331

In c# you can use Attributes, using this namespace

using System.ComponentModel;

You can add Description attribute to your enum elements

public enum ReportFileGeneratorFileType
{
    [Description("application/vnd.ms-excel")]
    Excel,
    [Description("application/pdf")]
    Pdf,
    [Description("application/vnd.ms-word")]
    Word
}

And using these methods you can "extract" a Dictionary<ReportFileGeneratorFileType, string> from your enum and use it on your code.

Upvotes: 1

gzaxx
gzaxx

Reputation: 17590

You should use Dictionary<key, value> as

var myArray = new Dictionary<ReportFileGeneratorFileType, string>();
myArray[ReportFileGeneratorFileType.Excel] = "application/vnd.ms-excel";

Upvotes: 3

Jacek Gorgoń
Jacek Gorgoń

Reputation: 3214

You could use an attribute (custom or built-int, such as DisplayNameAttribute) over the enum values to give them associated names/values. Example custom attribute follows:

public class ContentTypeAttribute : Attribute
{
    public string ContentType { get; set; }
    public ContentTypeAttribute(string contentType) 
    { 
         ContentType = contentType;
    }
}

public enum ReportFileGeneratorFileType
{
    [ContentType("application/vnd.ms-excel")]
    Excel,

    [ContentType("application/pdf")]
    Pdf,

    [ContentType("application/vnd.ms-word")]
    Word
}

To retrieve the content type based on an enum value, use:

...
ReportFileGeneratorFileType myType = ...
string contentType = myType.GetType()
    .GetCustomAttributes(typeof(ContentTypeAttribute))
    .Cast<ContentTypeAttribute>()
    .Single()
    .ContentType;
...

This may seem kind of complicated, but lets you keep content types (or whatever data) right on the enum itself, so you're not likely to forget adding it after adding a new type.

Upvotes: 2

Related Questions