2
votes

I was looking for a way to refactor and simplify one function where I have to do data sorting depending on input class type, and got stuck at switch(input.GetType()):

Quick search led me to Why doesn't C# switch statement allow using typeof/GetType()? with a link to http://blogs.msdn.com/peterhal/archive/2005/07/05/435760.aspx

I read the documentation, but I don't get the justification that the situation is confusing.

From the article:

Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:

class C {}
interface I {}
class D : C, I {}

switch typeof(e) {
case C: ... break;
case I: ... break;
default: ... break;
}

What's not simple about it? The call typeof(e) cannot return - this is a I D and C. It has to return a Type not an array of interface and class types - Type[]. So the type of the class D is D. And D corresponds to a default: branch.

An I missing something?

2

2 Answers

4
votes

It seems you don't expect the switch to match on subclasses. But this would break the Liskov Substitution Principle. (where if you passed in a C object, the code would work, but not with a D, even though D is a subclass of C).

3
votes

I think it's a perfectly valid argument on Peter Hallam's blog post that you don't expect switch statement to differ if you reorder things, so it's really only useful if only one branch can be valid at the same time, whereas with Type one class is always multiple different types along the inheritance chain.

No one stops you from doing this with an if...else chain, where you do expect it to be evaluated in the order you put things.