I have a ´switch´ which receives a object
. If I use a it list
works fine, but if I use a Dictionary
it doesn't work.
object data = DataStructureFactory.Make();
switch (data)
{
case IEnumerable<IEntity> listStackOrQueue:
// works
case IEnumerable<KeyValuePair<Guid,IEntity>> keyValuePair:
// don't works
case IDictionary<Guid,IEntity> dictionary:
// don't works
default:
throw new InvalidCastException(
"El tipo {0}, no pudo ser reconocido.",
data.GetType().Name);
}
When I run it I get the following error:
The type Dictionary`2, could not be recognized.
I noticed that the interface has the outIEnumerable
modifier , so I did some research on the matter and found about Variance in Generic Interfaces . I don't know if it has something to do with it, but I haven't solved the problem yet. IEnumerable<out T>
I see several things in the code,
with ":" instead of ";".
The names of the variables inside the switch (independent of the case to be evaluated) must be unique. You are using
model
for all cases.In the third case, you are placing as
expresión de tipo
an expression that (By derivation) you already have defined in the second case. That is, itIDictionary<Guid,IEntity>
implementsIEnumerable<KeyValuePair<Guid,IEntity>>
so thatcase
it would already be contemplated in the second case (Here a compiler error is thrown, because it is not allowed, but not because it is a casting error).In it
default case
you place a signatureInvalidCastException
that does not exist.As I see it, your code could look like this:
In the end I have decided to use
decorator desing pattern
and modify the data structures so that they implementIEnumerable<T>
.But I found a work around creating my own interfaces using Variance in Generic Interfaces .
In it
select case
I simply do the casting with the interfaces I create.Finally I leave the repository , in case you want to see the complete code.