C# Union Types Are Funny 0 ▲ Arialdo on Code 1 day ago · Tech · hide Can you predict the outcome of these simple unit tests? Say you have: record Case1; record Case2; union MyUnion(Case1, Case2); Test 1 MyUnion value = new Case1(); Assert.True(value.GetType() == typeof(MyUnion)); Green Red Won't compile... Correct! Wrong! Sure enough, Case1 is of type MyUnion. Test 2 With the previous code, the IDE suggests using the is operator: Why not? Let’s follow the suggestion. MyUnion value = new Case1(); Assert.True(value is MyUnion); // using the is operator Green Red Won't compile... Correct! Wrong! The is operation breaks the compilation. You get: An expression of union type MyUnion cannot be handled by a pattern of type MyUnion Fact is: the is operator implicitly unwraps union values and applies the pattern to their underlying case value, not to the union type itself. See C# 15 union types — .NET Blog. You cannot use it with the union type itself. Test 3 Let’s consider the Test 1 again: MyUnion value = new Case1(); What if you replace MyUnion with var? We… Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town