-
Notifications
You must be signed in to change notification settings - Fork 4.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proposal: switch on System.Type #8194
Comments
It's planned that you can switch on type in C# 7. I think it will look like this: switch(baz)
{
case Foo foo:
foo.DoFoo();
break;
case Bar bar:
bar.DoBar();
break;
} |
@GeirGrusom That's not what I'm talking about. |
Well, it would be nice if types were first-class citizens, but that would require CLR support, I think. |
@orthoxerox I even suspect that this behavior can be neatly implemented as an extension |
The CLR is fully capable of handling the logic. The question is how such a statement should be expanded. I'd imagine it would produce the same IL as a series of Type type = obj.GetType();
switch (type)
{
case typeof(Foo):
Console.WriteLine("Foo!");
break;
case typeof(Bar):
Console.WriteLine("Foo!");
break;
case typeof(Baz):
default:
Console.WriteLine("Baz or Something Else!");
break;
case typeof(Frob):
Console.WriteLine("Frob!");
break;
} effectively equivalent to: Type type = obj.GetType();
if (typeof(Foo).IsEquivalentTo(type))
{
Console.WriteLine("Foo!");
}
else if (typeof(Bar).IsEquivalentTo(type))
{
Console.WriteLine("Bar!");
}
else if (typeof(Frob).IsEquivalentTo(type))
{
Console.WriteLine("Frob!");
}
else
{
Console.WriteLine("Baz or Something Else!");
} |
@HaloFour |
@alrz In IL it's all conditional branch opcodes, unless the condition meets the incredibly narrow requirements to make it work with If |
Should this only match exact types? What about derived types? Would |
@drewnoakes That would be actually nice but then it will depend on the order and we might lose |
Or it'll turn it into a dictionary lookup, similar to VB.net's |
@CnSimonChan I think that's because |
@CnSimonChan Reported as #10459 |
Since we have to fix the compiler crash, lets just make this work. |
A compelling feature I come a lot across with. I'd love to see this implemented. |
Issue moved to dotnet/csharplang #356 via ZenHub |
When it comes to runtime type comparison, there are multiple ways to do so, it's more cumbersome if you want to do it multiple times with
if else
. it would be really nice if we could literallyswitch
onSystem.Type
orSystem.RuntimeTypeHandle
and compiler choose the fastest way, like usingTypeHandle
.The text was updated successfully, but these errors were encountered: