Mr. Boy
Mr. Boy

Reputation: 63836

Dictionary with Enum value type - calling the indexer for a key not in the dictionary?

I just ran into a slight problem. I have

IDictionary<Something,MyEnum> map;

I thought to write a method:

MyEnum GetMapping(Something x);

Used a bit like:

MyEnum e = GetMapping(x)
if(e!=null){...}

But of course the problem is since MyEnum is a standard Enum based on int, GetMapping cannot return null. Having to add a separate DoesMappingExist method seems messy, is there a neat way to address this?

And, what would map[AnObjectNotInTheMap] actually return - simply Default(MyEnum) i.e. 0?

Upvotes: 0

Views: 158

Answers (3)

Ye Peng
Ye Peng

Reputation: 183

The default value of Enum is 0. So you don't assign 0 to any member of MyEnum, 0 can indicate a no-mapping. This should be the easiest implementation unless 0 has to be allocated in MyEnum.

Upvotes: 0

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

You can use value-types as nullables using Nullable<T>, a shorthand for this is T?.

So, your code should be something like this:

MyEnum? GetMapping(Something x)
{
    if (...) return MyEnum.SomeValue;
    if (...) return MyEnum.OtherValue;

    return null;
}

Then, use it like this:

MyEnum? e = GetMapping(x);
if(e.HasValue)
{
    var mapped = e.Value;
    ...
}

Upvotes: 1

3615
3615

Reputation: 3885

Just go with nullable enum:

IDictionary<Something,MyEnum?> map;

And your method also changes as:

MyEnum? GetMapping(Something x);

Upvotes: 2

Related Questions