C
C#2y ago
SirCarter

❔ 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
basically, i am little cat
What if T1 and T2 are same type🤔
Thinker
Thinker2y ago
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.
SirCarter
SirCarterOP2y ago
Not override is Just get is to use an implicit operator from Either<T1, T2> to T1
Thinker
Thinker2y ago
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
public static implicit operator T1(Either<T1, T2> either) => ...;
public static implicit operator T1(Either<T1, T2> either) => ...;
SirCarter
SirCarterOP2y ago
Yes, and that works for assignment operations
Thinker
Thinker2y ago
However that will still not allow you to do either is T1 value, because an Either<T1, T2> isn't a T1.
SirCarter
SirCarterOP2y ago
Damn
Thinker
Thinker2y ago
is cannot be overwritten in any way and only checks if the value it's checking is the type you want.
SirCarter
SirCarterOP2y ago
Or assignable to, but I guess that doesn't include the conversions
Thinker
Thinker2y ago
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 works
SirCarter
SirCarterOP2y ago
Yeah I was trying to avoid something like that since but that's gonna be my default I wanted something a bit prettier 😭 Thanks though!
Thinker
Thinker2y ago
yeah unfortunately it's not a thing in C#, either/union types kind of suck
SirCarter
SirCarterOP2y ago
Praying for real unions one day
Thinker
Thinker2y ago
However there are ongoing discussions about implementing proper discriminated unions in C# $unionsdiscussion
MODiX
MODiX2y ago
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...
Thinker
Thinker2y ago
which would hopefully have nicer interactions with is
SirCarter
SirCarterOP2y ago
For anyone coming later, adding a nullable property getter reads fairly nicely: foo is {Left: {} left} I think that does what I want at least
Accord
Accord2y ago
Was 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.

Did you find this page helpful?