Unions in C# 15 and When to Use Them - Part of the .NET 11 Launch
Read full transcript 24 segments
-
Unions are the most talked about new feature in C# 15 which just came out as part of the .NET 11 launch. Let's look at what unions are and see how we can make use of them in a practical manner. Now if you don't know me, my name is Tim Corey and my goal is to help you become the best developer you can be. Instead of faking it or pretending that prompting an AI makes you good developer, I will teach you how to be a confident prepared developer ready to survive and thrive in today's marketplace. This channel has over a thousand videos dedicated just that. But if you're looking for even more go to devforge.com. There you'll find even more free and paid resources to help you wherever you are at on your developer journey. So let's jump right into what unions are. And if you didn't know by the way, um .NET 11 was just released. You might say well Tim you said C# 15. Yes, C# 15 is the language version which is always four ahead of the .NET version. So just note that when .NET 10 came out C# 14 came out and now the .NET 11 is out C# 15. Also note that .NET 11 yes is the standard term support or STS version but it is fully supported. It is production ready just the same as .NET 10 is. In fact it has the same remaining time of support as .NET 10 does. There's no difference there. So
-
let's look at what unions are and let's start with the problem. Here I've got a a very simple demo. This is all going to be in program.cs in a console app. Yes, this is a .NET 11 console app. So I have here a record called employee record and another record called contractor record and they're different, right? Contract employees are not the same thing as as full-time employees. And I have a list here of employees and I have a different list of contractors. Let's just pretend where I have two separate lists. This is just to kind of show you what unions can do. And we're going to start with what's the problem? Well, imagine I wanted to create a method. And let's just for now have it be a void method. I'm going to say look up worker. We're going to pass in a name. Well, how do I look up both employees and contractors and return one object? You can't return an employee sometimes and a contractor sometimes, right? So how would I how would I do that? Um and and let's start with um just doing a a quick lookup here. We're going to say equal e equals employees dot where we'll say x arrow uh string dot compare x dot name eq I'm I'm sorry, name.
-
Like so. And then we'll say is that equal to zero, meaning they're equal. And we're going to say first or default. And that's going to return either a null or the found record. And we'll do the same thing with contractor. So var c equals contractors where x arrow string dot compare x dot name and name and name passed in equals zero. And we're going to say first or default. So now we have two variables. Each of them either has a null value or an object of that particular type, either employee record for type or for var e or we're going to have the contractor record for var c. But how do we return this? That's a problem, right? So the way we used to do this and the way that if you have control of the types you could do is you could say well, I'm going to create an interface.
-
We'll call it i worker. And the only thing we're going do is say uh string name, and that's got to be it. Have it getter. Okay? And that's going to be my interface, and then I will come up here, I will say I worker. And I'll do the same thing for this record. And now what I could say is we'll actually return I worker. And then we're going to say um if E is not null, then return E. Because E is an I worker. And we'll do the same thing down here. If C is not null, then return C. We do have a problem though because we're not returning in all all the different paths because what if both are null?
-
In which case we have to return null. Well, that's not really great because you know we can say a a nullable I worker, but we can assume that yes, that could be nullable. Or we can do what typically happens is throw new not found um we'll just go through throw new exception um like so, and we can put a message here uh user not found. Or worker not found. And that's not ideal, but that would work, right? And so we come up here, and this is again, this is the old way of doing things. We're kind of cludging things together. We're going to show you how unions makes all this easier, but I want you to understand the problem first. So let's do a a simple do loop. Um and the reason why is because I'm going to say one equals one. Uh meaning loop forever.
-
And the reason why is I just want to make sure this this demo can go over and over and over again. So we're going to say uh console dot write uh what name should we look up? And then we'll do um string name to look up equals console.readline. Okay? Very simple stuff so far. We're just talking to the console. Okay. Now we're going to do is say var worker equals lookup worker and we'll say name to look up. And that's the name being passed in. By the way, we can mark this as never null um and that will take care of that exception. We could say or empty string, but but readline it says it it's a nullable string, but I don't know the case when it would ever return a null. It usually returns an empty string, so we're going to leave it alone for now for this demo.
-
Okay. So now what I want to do is I want to uh create a message that's, you know, tell me more about this user. So I'm going to say a string message equals worker and well actually they're all i worker, right? So how I do that? Actually I'm going to say worker um dot name and let's let's put this in a into you know some kind of string interpolation here um like [clears throat] so. And we'll say maybe it's name equals worker dot name, right? And then what we'll do is we're going to say console.readline message. Pretty simple. We're just going to say name is is Tim or Bob or Sue or whoever. um and then we're going to say console dot readline and then console.clear.
-
So what this does is it's going to loop infinitely. Now, you can have a cool demo that keeps working over and over and we can try different things without having to restart. So, it's going to say, hey, what name should you look up? It's going to look up either in this list or in this list and if it finds one, it's going to say the name is whoever and then it's going to wait for us to hit the enter key again and it's going to clear that out and start over. Let's just make sure this works as it is before we figure out how to make this a whole lot better with the unions. So, if I say Tim Corey, it's going to say name Tim Corey. If I say uh Bugs Bunny, so it's name Bugs Bunny. Okay, if I say Tim, it uh crashes the application with our exception, which is what we expect. But this is a little bit messy because it said name is Bugs Bunny, it said name is Tim Corey, but Bugs Bunny is a contract employee whereas Tim Corey is an employee.
-
We want different messages. Well, the way to do that is to have this this system that says, well, if the person is and then and then figure out what type of person they are. If they're employee, then do this and and cast it back from this interface. But what if instead of a null exception we wanted to return a string and say worker not found? Well, that won't work here because we have to have an interface which by the way we also have to have control over the employee record and contract record or contractor record. So, this is where unions makes all of this easier. So, let's look at what a union does. A union says, let's put it down here, um we're going to say union workers, which not intended, but okay, there you go, union workers. Um so, union workers, we're going to say employee record, contractor record, and we're going to also say string.
-
Now, what this is done is said this type called worker. This type is a union, and this union says that it could be the returning wrapped value could be an employee record, it could be a contractor record, or it could be a string. Those are the three things that I specified. Now, let's by the way get rid of our I worker. We don't have to have this interface, and that also means we don't have to control these records. These just whatever type we have access to, even types we don't have direct control over, like string. So now the lookup worker will return a workers or worker. That's the union type. Um so now it returns a worker instead of an I worker, which is an interface. So now it returns the actual type wrapped in a worker. It could be employee record, contractor record, or a string.
-
Now this right here, that's not going to work because it's not an interface anymore. But this is where we can do is a switch statement. So we can say uh worker switch and then have the various cases based upon the different types. Let's put our semicolon at the end before we forget it. So this is a switch expression, if you're not familiar. So a switch expression, by the way, it says hey um that does not handle all possible values of the input type. So what are the possible values for worker? Well, those possible values are employee record, contractor record, or string. So what we can do is we can say employee record E. If it's an employee record, then let's do some string interpolation here and say um let's go with e.employee ID and then we'll put a and then say e. name.
-
Notice I have full access to both like all the items in this employee record, not just whatever the interface had access to. So I can also say contractor record. We'll call it c and again do string interpolation. And in here we're going to say c. contractor ID colon and we'll say c. name from c. company. So now it's clear that they're different because one's from one's an employee we just have the employee ID and the name, the other one's a contractor ID and name from this company. And notice that the switch expression is still saying, hey, you haven't handled all the different types. Now sometimes if you don't want to handle all the types, what we used to do is do something like this where we'd say underscore arrow and then do something here, right? But that's not what we want to do here. Instead what we want to do is handle all the types. So string uh s and let's return the string itself.
-
So in that case we can say return worker not found. And it's not an exception, it's just the message that came back. So now notice the switch has been satisfied. It has three types. There is no default type here. It knows there's only three possible types, employee record, contractor record, and string. And notice it happen it does that at design time, not at runtime. Meaning you're not going to get surprised when you're in at runtime and find out, oh, we didn't handle a specific case or you're doing the generic we handle all other possibilities with this generic method. That's not a good idea. So now we have this this option. So you can say, what name you want to look up? Tim Core. Okay, it found one. That's my ID number, employee ID number, Tim Core.
-
How about Bugs Bunny? Now notice it has the employee record of Bugs Bunny, which is C001 and it says Bugs Bunny is from Acme Corp. And if I were to look up Sue, not Sue Storm but Sue, it's going to say worker not found. [snorts] No exceptions. It handles it properly. If I now find Sue Storm, it finds Sue Storm properly. Wile E. Coyote. It finds that Wile E. is from Acme Corp. Okay? So now this system is working a whole lot smoother because the fact that I can use a union and say these are the expected types. Now there is a different way you could have done this in the past as well, even if you didn't control things. And that would be instead of a union, you'd return an object.
-
So you could say object. And then you wouldn't have to have a union because object works just fine. The problem is you can't you don't know if that switch is handling all possibilities because the switch still works, right? So let's just run this real quick. Um Tim Core, still finds Tim Core. Bugs Bunny still finds Bugs Bunny and test worker not found. So that still works, but notice the switch expression is saying, hey, you haven't handled all the possible types because the return type is object. And that means that it could be one of any different type of object. I could return back in here and um, you know, anything, anything at all, which is a problem. So we have to do this case is you have to have the discard character here and say um, you know, throw new exception or something like that just to say that you have, you know, covered all your bases. But this right here is not a good thing because what happens down the road if um, you decide to add one more potential type?
-
So let's say that you want to create one more type of of record, maybe it is um, user record and you wanted that to be handled. Well, you wouldn't know that the user record is not being handled until you get to runtime and it tries to process a user and crashes. So instead, what happens is if you decide that you want to use unions, let's bring back our union here and come back up here to this and set obviously worker. If I wanted notice there's no no warnings here on switch. If I wanted to add a worker type and I were to say, you know what, uh record, let's create one uh uh demo record. String test, right?
-
Uh really simple stuff. Okay. So if I wanted this to return um, new test uh I'm sorry, new demo record like so. Well, uh this cannot implicitly convert demo record to worker because no, you can't do that. But let's just say I figured out how to get around that. Well, you can't because then up here it's going to yell at us too saying, hey, you haven't handled the demo record. So now what I have to do is come in here and say demo record. And all of a sudden things are looking good except for up here it's saying, hey, no, there's a warning here that you haven't handled all the possible types. And if you're doing warnings as errors, that will stop your build until you say, oh, I need to handle the the um the the demo possibility. In which case you can do something like this where you'd say demo record uh D and we're going to say um D dot test like so. Uh and that would work.
-
By the way, we're not um we have like return a string. That's okay. Um but now that works. We now have no more warning on switch. We have no more warning in our return type and we have everything handled because of the fact that we're at design time doing all of these checks as opposed to at runtime. Okay? So let's just go back to what we were doing with a string here, which by the way still works. Um still works everywhere. Um but if I were to take away the let's take away the demo record record tree here and whoops, just demo record. There we go. Um now we have a problem. We're up here. It says, hey, I can't do that. That's that's not one of the return types. So we get rid of that as a return type and we're good again. We can get rid of it here and we're back to where we were. So the union type allows us to return two different things or more that we do not necessarily control.
-
This can be really helpful for when you're returning from let's say an API and you might return the the uh object that is the the the looked up user, let's say. Or you can up the, you can send like a different object that is the why you couldn't find it. Or, you could also return an exception object, which is a different type of object. And then you'd know all these are the three things that might be coming back. So, same thing with inputs and and many other things. Unions are super helpful for allowing us to have design time checks on our data. So, that way we're not going down to the object level to make sure they work. We can still do a switch and know that the switch handles all the cases possible, that when we return something, that we are returning one of the potential types, not just anything.
-
And it's being very very diligent to make sure at design time that we have all of our checks in place. Okay? So, that's what workers do. That's why they are so valuable. Now, real quick note here is that this is, when you put it into a union, we put object, return an object as a union type. What it's doing is an implicit conversion. But, there is a bit of a, which is, you know, totally fine and not a problem and no performance issue. But, there is a little tiny tiny, but there's an issue. Not an issue. There's a performance thing to think about. And that is if you return a a uh a value type, not a reference type. Notice uh reference type, reference type, reference type, right? So, well, special reference type right there. But, uh reference types.
-
However, if you return a or make a int as a possible object item in the union type, what actually happens is it boxes the int. Okay? If you remember back to when we talked about boxing before, uh value types and reference types, uh the the boxing works is it essentially creates an object on the heap. And in that object, it puts your integer. So, that's the one thing it's doing that is a um is less performance than the rest of these things. Okay? The rest of these things they're very very performant. This one is slightly less. But, I want to be very clear here, this is not a performance problem. The only time that it would be a performance problem is if you are say boxing and unboxing these integers millions of times or hundreds of thousands of times. And that shouldn't be the case for what you're doing here.
-
Um that shouldn't be a problem. But, I want you to know that that's happening. You should understand what's going on underneath the hood whenever you're using something. That way you don't accidentally abuse it. So, just note that if you're putting value types in here, they are getting boxed. Okay? So, that is the union type. There's more to it. Um there's more things you can do with union. Uh for example, we we could have moved um this code right here into the union itself. Um and so it returns, you know, we could say, hey give me just the the a string the message. But, I don't love doing that in most cases. Uh it it's great for a demo and it's great for certain specific cases, but it's not an everyday thing I would do. And the reason why is because up here, yes, I'm just building out a string based upon employee record. However, in the real world, I probably calling out to a method and passing an employee record.
-
And doing something different than contractor record. And now I have the full type object, strongly typed object that I can pass around and do things with as opposed to just a string that comes back that's different bit depending on the the object type. Great for demos. Um not as much something I would use in the real world as getting the actual types back. So, unions are a way to be more efficient, to improve performance because you're not doing objects and trying to you know cast back and forth. Um you've got the union type. It's also making sure that you are uh design time checking your values to make sure there's no assumptions in here, to make sure that when you change the code later that it doesn't break something. Um all these design time checks will happen as opposed to finding out at runtime when your customer calls you and says, hey the thing is breaking now because of a a new type that you put into your object.
-
Okay? So that's unions, that's how they work. More to come on this as well as the other um C Sharp 15 and .NET 11 uh stuff that has been released recently. Thanks for watching. As always, I am Tim Corey. >> [music] [music]
Summary
This video explores the new union feature introduced in C# 15 alongside the .NET 11 release, demonstrating how it solves traditional challenges of returning multiple distinct types from a single method. The discussion compares legacy approaches—such as utilizing interfaces, shared base classes, or throwing exceptions for null values—with the streamlined capabilities of unions. The practical takeaway is that C# 15 unions provide a cleaner, more efficient way to handle disparate data types without the need for cumbersome workarounds or cludged type hierarchies.