Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#8: Switch ref expressions

I can't figure out how to make a switch expression yield a ref value.

bool cond = true;
int a = 1, b = 2;

// This works
ref int c = ref cond ? ref a : ref b;

// But using a switch expression fails to compile.
// Error CS1525 Invalid expression term 'ref'
c = ref (cond switch { true => ref a, false => ref b });

Am I getting the syntax wrong? Is this even possible?

It doesn't compile regardless of whether I include the outer ref ( ) part. I used a bool only to quickly illustrate the question, but my actual use case is not so simple.

like image 573
recursive Avatar asked Nov 22 '19 01:11

recursive


1 Answers

Yes, the syntax is wrong. This is pretty clear because of the compiler error code you noted in your question (CS1525).

Why? The switch expression appears to be incompatible with refs.

Don't fight the compiler, just write the code in a way that works and is easy to read. Here's the old-school way to write it:

ref int c = ref a;

if (!cond)
{
    c = ref b;
}
like image 87
robbpriestley Avatar answered Nov 03 '22 17:11

robbpriestley