0

I have an enum with some status values:

public enum Status
{
    New = 0,
    Dropped = 1,
    Approved = 2
}

Is it possible to make a default casting such an enum? A default casting that cast each Status to a specific Image without requiring an explicit conversion?

Thanks.

Jehof
  • 34,674
  • 10
  • 123
  • 155
user2500179
  • 291
  • 1
  • 2
  • 6
  • 3
    What `Image` type are you referring to here? If it's your own class you *could* add an implicit conversion, but personally I wouldn't. – Jon Skeet Sep 24 '13 at 07:57

1 Answers1

2

Why cant you just make a Dictionary?

public class StatusHelper
{
    private Dictionary<Status, Image> _map;

    public StatusHelper()
    {
        _map = new Dictionary<Status, Image>()
                       {
                           {Status.New, new Image()},
                           {Status.Dropped, new Image()},
                           {Status.Approved, new Image()},
                       };
    }

    public Image GetImageForStatus(Status status)
    {
        return _map[status];
    }
}

Why do it this way? Well because you can inject your mapping with IoC (example here)

So, this becomes;

public StatusHelper(Dictionary<Status, Image> injectedMap)
{
    _map = injectedMap;
}

and somewhere in your app you set up a Bind (not tested, only an example)

Bind<Dictionary<Status, Image>>()
  .ToConstant(new Dictionary<Status, Image>()
                   {
                       {Status.New, new Image()},
                       {Status.Dropped, new Image()},
                       {Status.Approved, new Image()},
                   })
  .WhenInjectedInto<StatusHelper>();

Now you're helper is oblivious to any change you make to Status or its images

Community
  • 1
  • 1
Meirion Hughes
  • 24,994
  • 12
  • 71
  • 122
  • "because you can inject your mapping with IoC" Two questions: 1) why is that a good thing? 2) those images would probably come from files, resources or URLs, which could be configurable _if_ _needed_. Maybe they are loaded from a database or files, and they can be modified _if_ _needed_. Why would IoC be better than the alternatives in those cases? – Kris Vandermotten Sep 24 '13 at 08:14
  • Well, off hand lets say I have a single library used by 10 applications... I can alter the behavior of the library classes for each of my applications, because I'm injecting the information they need to work. i.e I can have different images for these Status enums for different applications, without altering any of the classes – Meirion Hughes Sep 24 '13 at 08:18