Created
March 13, 2020 13:22
-
-
Save KvanTTT/abf037a06aa525b4e4ffa6246199d463 to your computer and use it in GitHub Desktop.
Compare generated code for switch by object vs switch by int
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class C { | |
public const int C1Type = 1; | |
public const int C2Type = 2; | |
public const int C3Type = 3; | |
public const int C4Type = 4; | |
public abstract class Base | |
{ | |
public abstract int Type { get; } | |
} | |
public class C1 : Base { | |
public override int Type => 1; | |
} | |
public class C2 : Base { | |
public override int Type => 2; | |
} | |
public class C3 : Base { | |
public override int Type => 3; | |
} | |
public class C4 : Base { | |
public override int Type => 4; | |
} | |
public void M() { | |
} | |
public void PatternMatching(Base b) | |
{ | |
switch (b) | |
{ | |
case C1 c1: | |
Console.Write(c1); | |
break; | |
case C2 c2: | |
Console.Write(c2); | |
break; | |
case C3 c3: | |
Console.Write(c3); | |
break; | |
case C4 c4: | |
Console.Write(c4); | |
break; | |
} | |
} | |
public void SwitchByInt(Base b) | |
{ | |
switch (b.Type) | |
{ | |
case C1Type: | |
Console.Write((C1)b); | |
break; | |
case C2Type: | |
Console.Write((C2)b); | |
break; | |
case C3Type: | |
Console.Write((C3)b); | |
break; | |
case C4Type: | |
Console.Write((C4)b); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment