C
C#15mo 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
Thinker15mo 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
SirCarter15mo ago
Not override is Just get is to use an implicit operator from Either<T1, T2> to T1
Thinker
Thinker15mo 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
SirCarter15mo ago
Yes, and that works for assignment operations
Thinker
Thinker15mo ago
However that will still not allow you to do either is T1 value, because an Either<T1, T2> isn't a T1.
SirCarter
SirCarter15mo ago
Damn
Thinker
Thinker15mo ago
is cannot be overwritten in any way and only checks if the value it's checking is the type you want.
SirCarter
SirCarter15mo ago
Or assignable to, but I guess that doesn't include the conversions
Thinker
Thinker15mo 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
SirCarter15mo 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
Thinker15mo ago
yeah unfortunately it's not a thing in C#, either/union types kind of suck
SirCarter
SirCarter15mo ago
Praying for real unions one day
Thinker
Thinker15mo ago
However there are ongoing discussions about implementing proper discriminated unions in C# $unionsdiscussion
MODiX
MODiX15mo 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
Thinker15mo ago
which would hopefully have nicer interactions with is
SirCarter
SirCarter15mo 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
Accord15mo 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.