❔ User-defined implicit type conversion + type pattern match
Hello, if I have some type
Either<T1, T2>
that has a left and right variant, is there a way to get C# to use an implicit converter so that I can write: foobar is T1 value
?18 Replies
What if T1 and T2 are same type🤔
If you mean to "override"
is
then no, you can't
Best you can do is have IsLeft
and IsRight
properties in your Either<T1, T2>
type.Not override is
Just get is to use an implicit operator from
Either<T1, T2>
to T1
oh
Well, firstly imo that would probably be better as an explicit operator rather than an implicit one, as the value may not exist
But you can do
Yes, and that works for assignment operations
However that will still not allow you to do
either is T1 value
, because an Either<T1, T2>
isn't a T1
.Damn
is
cannot be overwritten in any way and only checks if the value it's checking is the type you want.Or assignable to, but I guess that doesn't include the conversions
However you could maybe have a helper method so you can do
if (either.AsT1(out T1 value)) { ... }
which is a bit more terse but worksYeah I was trying to avoid something like that since but that's gonna be my default
I wanted something a bit prettier 😭
Thanks though!
yeah unfortunately it's not a thing in C#, either/union types kind of suck
Praying for real unions one day
However there are ongoing discussions about implementing proper discriminated unions in C#
$unionsdiscussion
GitHub
[LDM] - Union Types · dotnet csharplang · Discussion #7010
The following is a summary of discussions held on discriminated unions in C# by members of the C# language design team. It is not a proposal, and it is not the actual meeting notes. Union Types Uni...
which would hopefully have nicer interactions with
is
For anyone coming later, adding a nullable property getter reads fairly nicely:
foo is {Left: {} left}
I think that does what I want at leastWas this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.